I have rest controller which is returning HttpResponseMessage with Stream file as a content, something like this:
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);
}
}
}
When i call this method by ULR in browser everything is ok and i can download this file. Now i would like to download it using Swagger UI. Is some easy way to do this?
In case someone else is looking for this, I did the following:
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>();
});
This is what worked for me (.Net Core 2.2 and 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With