Home >Backend Development >C++ >How to Return a File Instead of JSON in ASP.Net Core Web API?

How to Return a File Instead of JSON in ASP.Net Core Web API?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 07:04:30465browse

How to Return a File Instead of JSON in ASP.Net Core Web API?

Returning a File in ASP.Net Core Web API

Problem:

When attempting to return a file in an ASP.Net Core Web API controller, the HttpResponseMessage is being returned as JSON with an application/json content header, rather than as a file.

Code Attempt:

public async Task<HttpResponseMessage> DownloadAsync(string id)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent({{__insert_stream_here__}});
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return response;
}

Cause:

The HttpResponseMessage is being treated as a model by the web API framework because it is being returned from an action that is decorated with the [HttpGet] attribute.

Solution:

To correctly return a file, modify the controller action to return an IActionResult:

[Route("api/[controller]")]
public class DownloadController : Controller
{
    //GET api/download/12345abc
    [HttpGet("{id}")]
    public async Task<IActionResult> Download(string id)
    {
        Stream stream = await {{__get_stream_based_on_id_here__}};

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream", "{{filename.ext}}"); // returns a FileStreamResult
    }    
}

Note:

The framework will dispose of the used stream after the response is completed. Using a using statement to dispose of the stream before the response is sent will result in an exception or corrupt response.

The above is the detailed content of How to Return a File Instead of JSON in ASP.Net Core Web API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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