Home > Backend Development > C++ > body text

How to Return Files from ASP.Net Core Web API Without JSON Formatting?

Barbara Streisand
Release: 2024-10-31 18:16:02
Original
391 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!