簡體   English   中英

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

你不能這樣做,因為它不會返回 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 ,請參見此處


另一個變體是使用SwaggerResponse屬性,它也允許提供額外的描述:

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

它產生如下所示的輸出:

在此處輸入圖片說明 在此處輸入圖片說明

也可以省略類型以記錄不返回實體的其他狀態代碼:

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

在此處輸入圖片說明

您可以使用以下屬性指定響應類型:

[ProducesResponseType(typeof(UserCreateResponse), 200)]

從 .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(...) 
{
   ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM