Swashbuckle - 返回响应的大摇大摆的文档?

Swashbuckle - swagger documentation of returned response?

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);
    }

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

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

        //do something here

        // returns UserCreateResponse
        return response;
    }

您可以使用以下属性指定响应类型:

[ProducesResponseType(typeof(UserCreateResponse), 200)]

以下解决方案仅适用于 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);
}

产生如下所示的输出:

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

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

从 .NET Core 2.1 开始,使用 ActionResult<T> 将是指定返回类型的推荐方法。它被 Swashbuckle 选中,并在编译时添加了类型检查。

您还可以通过 XML 评论 (docs) 添加对回复的描述。

因此对于 OP 的示例,它将是

/// <summary> 
///     Update the user 
/// </summary>
/// <response code="200"> User's data </response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<UserCreateResponse>> Update(...) 
{
   ...
}