如何设置从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)
...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...