Home > Article > Backend Development > How to Return Files from ASP.Net Core Web API Without JSON Formatting?
Returning Files in ASP.Net Core Web API
Problem:
Web API controllers often require the ability to return files. However, users may encounter issues where the returned HttpResponseMessage is formatted as JSON, even when steps are taken to set the ContentType as application/octet-stream.
Solution:
In ASP.Net Core, utilizing the IActionResult interface for actions addresses this issue. The framework interprets HttpResponseMessage as a model with this approach.
Here's how to implement it:
<code class="csharp">[Route("api/[controller]")] public class DownloadController : Controller { [HttpGet("{id}")] public async Task<IActionResult> Download(string id) { Stream stream = await GetStreamByIdAsync(id); if (stream == null) return NotFound(); // Returns a NotFoundResult with Status404NotFound response. return File(stream, "application/octet-stream", $"{filename.ext}"); // Returns a FileStreamResult } }</code>
Note:
The framework will automatically dispose of the stream after the response is complete. Using a using statement prematurely will result in exceptions or a corrupted response.
The above is the detailed content of How to Return Files from ASP.Net Core Web API Without JSON Formatting?. For more information, please follow other related articles on the PHP Chinese website!