Net Core Swagger UI - 获取路由 - 不向用户显示参数验证

NetCore SwaggerUI - Get Route - Validations for parameters are not displayed to user

我正在尝试在我的 WebApi (Net 5) 中定义一种使用 2 个路由参数的“GET”路由,它们需要验证,参数来自路由。我也需要在其他控制器中执行相同模式的多项操作。因此,我尝试像在 POST 中那样使用 ValidationAttribute,SwaggerUI 知道参数何时出现错误,并知道参数何时有效但不显示错误。

ex:
/calendar/year/month

year must be between 2020 AND 2030
month must be between 1 AND 12

所以,我从这样的事情开始

public class YearMonth
{
    [Range(2020, 2030, ErrorMessage = "The year must be between 2020 AND 2030")]
    public int Year { get; set; }

    [Range(1, 12, ErrorMessage = "The month must be between 1 AND 12")]
    public int Month { get; set; }
}

[HttpGet("{Year}/{Month}")]
public async Task<ActionResult<Calendar>> Get([FromRoute] YearMonth yearMonth)
{

}

我的问题是 Swagger UI 知道验证,因此如果年份或月份未通过验证,它不会触发请求。显示字段有误!

但是 UI 中没有任何内容说明为什么会出现错误或错误到底是什么!

有没有办法添加验证错误?

或者有没有办法添加标签来描述验证?

当我们 post 数据到 API 时,它执行请求,即使对象无效并且 return HttpResponseMessage 有错误,我期待与 Get 方法相同!

在您的 Swashbuckle 配置中,使用:

app.UseSwaggerUI(c =>
{
    ...
    c.ShowCommonExtensions();
});

这指示 Swagger UI 显示输入参数的定义最小值和最大值。


It show that the field is in error! But there is nothing in the UI that show why there is an error or what is the error exactly!

如果将鼠标悬停在红色字段上,它将显示一个工具提示,其中包含一条错误消息,例如“值必须大于 2020”。