【问题标题】:ASP.net Core Web API - correct swagger annotationsASP.net Core Web API - 正确的招摇注释
【发布时间】:2020-05-17 22:29:20
【问题描述】:

我正在编写一个 Web API,并定义了一个具有各种 GET、POST 方法等的控制器。我正在为我的文档使用 Swagger Open API,并希望了解正确的注释方法。这是我拥有的控制器方法的示例:

/// <summary>Download a file based on its Id.</summary>
/// <param name="id">Identity of file to download.</param>
/// <returns><see cref="MyFile" /> file content found.</returns>
[HttpGet("download/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[SwaggerResponse(200, "Myfile content", typeof(MyFile))]
[SwaggerResponse(404, "Could not find file", typeof(MyFile))]
public async Task<IActionResult> DownloadAsync(int id)
{
    const string mimeType = "application/octet-stream";
    var myFile = await _dbContext.MyFiles.FindAsync(id);

    // If we cannot find the mapping, return 404.
    if (myFile.IsNullOrDefault())
    {
        return NotFound();
    }

    // Download using file stream.
    var downloadStream = await _blobStorage.DownloadBlob(myFile.FileLocation);
    return new FileStreamResult(downloadStream, mimeType) { FileDownloadName = myFile.FileName };
}

如您所见,我同时使用 ProducesResponseType 和 SwaggerResponse 来描述下载方法。我对使用的正确属性有点困惑 - 招摇响应还是产生响应类型?我应该同时使用吗?为什么我会偏爱其中一个?

提前感谢您的任何指点! :)

【问题讨论】:

    标签: c# asp.net-core asp.net-web-api swagger openapi


    【解决方案1】:

    不需要同时使用ProducesResponseTypeSwaggerResponse。 它还取决于您的操作声明,例如您的操作返回Task&lt;IActionResult&gt;

    只知道(没有任何附加属性)该操作的返回类型可能是任何东西。

    因此,通过向该方法添加:[SwaggerResponse(200, "Myfile content", typeof(MyFile))] 属性,类型 MyFile 已知会从该操作返回并且可以记录在案。

    另一方面,如果您在返回类型中指定如下,则不需要该属性:

    [HttpGet("download/{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<MyFile>> DownloadAsync(int id)
    

    我删除了 2 个SwaggerResponse 属性,记录的此操作的返回类型仍然相同。

    我会说注释越少越好,但这当然取决于您的需求;p

    【讨论】:

      【解决方案2】:

      在我的例子中,我已经在使用“SwaggerOperation”注释来为操作添加摘要和描述(强烈推荐),这就是我继续使用 SwaggerResponse 而不是 ProducesResponseType 的原因。最后真的应该没关系,从源码中可以看出 SwaggerResponseAttribute 是从 ProducesResponseTypeAttribute 派生的:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-26
        • 2018-11-07
        • 1970-01-01
        • 2019-03-19
        • 2017-12-09
        • 2023-03-11
        相关资源
        最近更新 更多