如何解决如何设置从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://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)
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。