我有一个返回数组的控制器方法:
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
//[MaxLength(10)] // <- !!!!!!!!!!!!!!
public IEnumerable<WeatherForecast> Get([FromQuery] WeatherForecastQuery query)
...
已经为该控制器生成了一个swagger规范,该规范描述了一系列没有最小/最大项属性的响应
...
"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://learn.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)
...