'how to get file download in swagger UI?
I need to generate a link in swagger in result which will download the file, but none of the solutions privded seem to work for me see my code -
'''
[HttpGet]
/// <response code="200">success</response>
[SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
[Route("api/Controller/DownloadFile")]
public ActionResult DownloadFile(string fileName)
{
try
{
var bytes = System.IO.File.ReadAllBytesAsync("\\\\test-dm.com\\testfile\\" + fileName);
return PhysicalFile("application/pdf", Path.GetFileName("\\\\test-dm.com\\testfile\\" + fileName));
}
catch (Exception ex)
{
var bytes = new byte[0];
return File("text/plain", "test.pdf"); ;
}
}
'''
See my startup -
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "M2PPortal", Version = "v1" });
});
[enter image description here][1]
see image [1]: https://i.stack.imgur.com/VwcG1.jpg
i have seen only where other have download file link is coming, how should i configure for it.
This is my first question here, let me know if there are any issues in my query or any other info is required.
Solution 1:[1]
See result image, which was as expectedUsing below code gave the expected result, basically a link to the file -
[HttpGet]
/// <response code="200">success</response>
[SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
[Route("api/Controller/DownloadFile")]
public FileContentResult DownloadFile(string fileName)
{
try
{
return File(System.IO.File.ReadAllBytes(_configuration.GetValue<string>("FilePath:PathofFiles") + fileName), "application/pdf", fileName);
}
catch (Exception ex)
{
// write a generic return value which could be used to handle error
}
}
using FileContentResult instead of action or ActionResult or HttpResponseMessage. No changes where required in Configureservices or configure
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Satyam Singh |
