c# - Swashbuckle - 返回响应的 Swagger 的文档?

标签 c# rest asp.net-core swagger swashbuckle

Swashbuckle 不会生成带有“UserCreateResponse”输出的 swagger.json,您如何解决这个问题?

    [HttpPost]
    public async Task<IActionResult> Update([FromBody]UserCreate Request)
    {
        UserCreateResponse response = new UserCreateResponse();

        //do something here

        // returns UserCreateResponse with http status code 200
        return Ok(response);
    }

你不能这样做,因为它不会返回 http 状态代码,200,400,401 等

    [HttpPost]
    public async Task<UserCreateResponse> Update([FromBody]UserCreate Request)
    {
        UserCreateResponse response = new UserCreateResponse();

        //do something here

        // returns UserCreateResponse
        return response;
    }

最佳答案

以下解决方案仅适用于 V6.0 之前的 Swashbuckle 版本!

从 V6.0 开始不再支持 SwaggerResponse,请参阅 here .


另一种变体是使用 SwaggerResponse 属性,它还允许提供额外的描述:

[SwaggerResponse(HttpStatusCode.OK, "UserDTO", typeof(UserDTO))]
public async Task<IHttpActionResult> Get([FromODataUri] int key)
{
    var result = await UserRepo.GetAsync(key);
    ...
    return Ok(result);
}

产生如下所示的输出:

enter image description here enter image description here

也可以省略类型来记录不返回实体的其他状态代码:

[SwaggerResponse(HttpStatusCode.NotFound, "no data found")]
[SwaggerResponse(HttpStatusCode.BadRequest, "requiered request headers not found")]

enter image description here

关于c# - Swashbuckle - 返回响应的 Swagger 的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45182448/

相关文章:

c# - 如何使用 IHttpClientFactory 刷新 token

c# - 如何在gridview中绑定(bind)变量值?

javascript - 从 Angular js 资源获取数据

entity-framework - 使用ASP.NET Core无法识别的MySQL扩展方法

c# - 通用列表和值引用

c# - 未使用 IdentityServer3 持有者 token 调用 WebAPI 授权属性

java - mockMvc POST Junit 测试因 HttpMessageNotReadableException 失败

java - 微服务架构,在这种情况下什么是服务

c# - 有没有办法在 ASP Net/ASP Net Core 中使用 URL 路径段中的参数

c# - 如何在 ASP.NET Core MVC 中显示特定的 ModelState 错误?