如何使用 Swagger UI 下载文件

luk*_*hol 6 c# asp.net-web-api swagger

我有休息控制器,它以流文件作为内容返回 HttpResponseMessage,如下所示:

public class MyController : ApiController
{
    public HttpResponseMessage GetFile(string id)
    {
        try { 
            var stream = fileSystemUtils.GetFileStream(filePath); //Get Stream
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = stream;
            return response;
        }
        catch (FileNotFoundException)
        {
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中通过 ULR 调用此方法时,一切正常,我可以下载此文件。现在我想使用 Swagger UI 下载它。有什么简单的方法可以做到这一点吗?

Mar*_*llo 8

这对我有用(.Net Core 2.2 和 Swashbuckle 4.0.1):

[Route("api/[controller]")]
[ApiController]
public class DownloadController : ControllerBase
{
    [HttpGet("{name}")]
    [ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(BadRequestObjectResult), 400)]
    public async Task<IActionResult> GetFile(string fileName)
    {
        var filePath = $"files/{fileName}"; // get file full path based on file name
        if (!System.IO.File.Exists(filePath))
        {
            return BadRequest();
        }
        return File(await System.IO.File.ReadAllBytesAsync(filePath), "application/octet-stream", fileName);
    }
}
Run Code Online (Sandbox Code Playgroud)


Bia*_*nca 6

如果其他人正在寻找这个,我做了以下事情:

public class FileOperation : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.OperationId.ToLower() == "apifileget")
        {
            operation.Produces = new[] { "application/octet-stream" };
            operation.Responses["200"].Schema = new Schema { Type = "file", Description = "Download file"};
        }
    }
}

//In the startup...
services.AddSwaggerGen(c =>
{
    //missing code...
    c.OperationFilter<FileOperation>();
});
Run Code Online (Sandbox Code Playgroud)