如何使用Swagger UI下载文件

时间:2017-05-22 17:22:01

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

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

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

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

2 个答案:

答案 0 :(得分:2)

如果其他人正在寻找此项,我会做以下事情:

transform: Translate

答案 1 :(得分:2)

这对我有用(.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);
    }
}