如何设置从metod返回的IEnumerable的MaxLengthAttribute用于生成swagger maxItems属性

问题描述

我有一个返回数组的控制器方法

[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    //[MaxLength(10)]   // <- !!!!!!!!!!!!!!
    public  IEnumerable<WeatherForecast> Get([FromQuery] WeatherForecastQuery query)
...

为此控制器生成一个摇摇欲坠的规范,它描述了没有min / maxItems属性的响应数组

  ...
  "responses": {
      "200": {
        "description": "Success","content": {
          "application/json": {
            "schema": {
              "type": "array","items": {
                "$ref": "#/components/schemas/WeatherForecast"
              },//minItems: 1,// <- I want it
              //maxItems: 10,// <- I want it
            }}}}}
  ...

如何将min / maxItems属性添加方法返回数组?

解决方法

MaxLengthAttribute不是方法允许的属性,

目标是

[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property,AllowMultiple=false)]

https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netcore-3.1

另请参阅:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1747

,

您必须将数据注释[MaxLength(10)]放入您的WeatherForecastQuery对象。我认为该对象包含IEnumerable吗?

更新

如果我现在正确理解了,您最多希望返回10条条目。

您可以返回一个这样的新对象

public class GetWeatherForecastResponse {
     [MaxLength(10)]
     public IEnumerable<WeatherForecast> Result { get; set; }
}

那么您的控制器应该看起来像这样

[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public GetWeatherForecastResponse Get([FromQuery] WeatherForecastQuery query)
...