When attempting to return a file from an ASP.NET Web API Controller, you may encounter issues with the response being treated as JSON. To resolve this, it's crucial to understand the correct approach to file download in ASP.NET Core.
To return a file in ASP.NET Core Web API, you need to return a derived IActionResult instead of HttpResponseMessage. The framework will interpret HttpResponseMessage as a model, leading to the JSON response issue.
Below is an updated code example that demonstrates how to return a file using IActionResult:
[Route("api/[controller]")]
public class DownloadController : Controller
{
// GET api/download/12345abc
[HttpGet("{id}")]
public async Task Download(string id)
{
Stream stream = await GetStreamBasedOnIdAsync(id);
if (stream == null)
return NotFound(); // Returns a NotFoundResult with Status404NotFound response
return File(stream, "application/octet-stream", $"{FileName}.{FileExtension}"); // Returns a FileStreamResult
}
}
Note: Do not use a using statement for the stream; otherwise, it will be disposed of before the response has been sent, resulting in an exception or corrupt response. The framework will handle stream disposal automatically when the response is completed.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3