c# - SwashBuckle 定义错误时的响应主体

标签 c# asp.net-core swagger swashbuckle

我的应用程序是一个 ASP.NET Core 1.0 Web API。

我有以下 Controller :

    [HttpGet("{someData:MinLength(5):MaxLength(5)}")]
    [Produces("application/json")]
    public async Task<IActionResult> GetSomeData(string someData)
    {
        return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));
    }

每当我传递例如字符串“111”时,swagger 都会向我显示以下消息:

enter image description here

我怎样才能获得像这样的响应主体:

“请输入5个数字”

谢谢

最佳答案

您可以使用 [ProducesResponseType(typeof(ModelStateDictionary), (int)HttpStatusCode.OK)] 注释您的操作,以返回典型的字典类型的错误消息,例如使用 return BadRequest(ModelState) )

但是您不能在模式定义中返回文本。它用于 json 结构,而不用于错误消息。相反,您应该使用 xmldoc(并在 swagger 中启用它)来为参数添加描述。

更新:添加参数及其含义文档的替代方法

/// <summary>
/// Returns some data based on <paramref name="someData"/> parameter.
/// </summary>
/// <param name="someData">Some data. (Must be exactly 5 characters wide)</param>
/// <response code="200">Returns indexed tags on success</response>
/// <response code="400">Invalid data sent</response>
/// <returns>A paged list of results</returns>
[HttpGet("{someData:MinLength(5):MaxLength(5)}")]
[ProducesResponseType(typeof(MyReturnType), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetSomeData(string someData)
{
}

您还需要在项目的属性中启用 xmldocs 的构建。

并添加到您的启动:

services.AddSwaggerGen(options =>
{
    ...
    var appEnv = PlatformServices.Default.Application;

    options.IncludeXmlComments(Path.Combine(appEnv.ApplicationBasePath, $"{appEnv.ApplicationName}.xml"));
    ...
});

关于c# - SwashBuckle 定义错误时的响应主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42974559/

相关文章:

c# - 如何跳过 foreach 循环的值?

c# - 有没有办法检查串口(RS-232)连接设备的电源开/关?

asp.net-core - 如何在具有 maxAllowedContentLength 的 IIS 上的 ASP.NET Core 中使用 MaxRequestBodySize?

amazon-web-services - AWS API 网关 : Documentation Swagger export model type null ignored

java - 通过jetty.xml进行Swagger UI配置

c# - 为什么我的属性的支持字段没有改变它的值?

c# - 如何为 blazor 应用程序以像素为单位查找 svg 文本大小?

c# - 如何从登录用户获取 "B2C JWT Access Token"?

c# - 使用授权属性时的 Cors 策略错误

限制 Swagger UI 访问 - 用户登录