使用dotnet core返回Swagger文档的文件类型

chr*_*389 6 c# swagger .net-core asp.net-core-webapi

我正在使用Swagger作为dotnet核心来记录我的dotnet核心Web API.

我已阅读文档告诉我,我需要[ProducesResponseType(typeof(XXXXX),200)]在控制器方法上面添加 以帮助swagger确定方法的响应类型.

我有一个控制器方法返回一个文件,我试图弄清楚我怎么能告诉swagger我正在返回一个文件.

public class DocumentController : Controller
{
    private readonly IDocumentService _documentService;

    public DocumentController(IDocumentService documentService)
    {
        _documentService = documentService;
    }

    [HttpGet("{documentId}", Name= DocumentRoutes.Document)]
    [ProducesResponseType(typeof(XXXXX), 200)] // <== What goes here?
    public async Task<IActionResult> GetDocument(Guid documentId)
    {
        DocumentAdto documentAdto = await _documentService.GetAsync(documentId);
        return File(documentAdto.DocumentBytes, documentAdto.ContentType, documentAdto.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有人有任何想法?

我已经考虑过byte [],但只是说返回类型是"byte".

Moh*_*oho 6

您需要的是ProducesAttribute并指定内容类型作为参数(例如PDF文件的"application/pdf").

编辑:看来Swagger可能不会接受ProducesAttribute.我的建议是留下未Type设置的ProducesResponseType/// <response code="200">Returns the requested file</response>为方法添加注释.

  • 返回文件是响应,是内容类型,而不是表示 json 或 xml 文档架构的 `ProducesResponseType`。如果 Swagger 没有在操作方法上选择“ProducesAttribute”,那么我只需将“ProducesResponseType”的“Type”保留为未设置,并使用“&lt;response code="200"&gt;返回请求的文件&lt;/response&gt; ` 评论 (2认同)