Home >Backend Development >C++ >How to Return Files from an ASP.NET Core Web API?

How to Return Files from an ASP.NET Core Web API?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 09:20:02307browse

How to Return Files from an ASP.NET Core Web API?

Download Files in ASP.NET Core Web APIs

Returning files from an ASP.NET Core Web API can be challenging, as the default behavior often results in the HttpResponseMessage being serialized as JSON. To address this issue, we need to utilize a different approach.

In the provided code snippet, the IActionResult interface should be used to return a derived ActionResult type. By returning a FileStreamResult, we can specify the content type and filename of the file to be downloaded.

<code class="csharp">[Route("api/[controller]")]
public class DownloadController : Controller
{
    [HttpGet("{id}")]
    public async Task<IActionResult> Download(string id)
    {
        Stream stream = await GetStreamBasedOnIdAsync(id);

        if (stream == null)
            return NotFound();

        return File(stream, "application/octet-stream", $"{filename}.ext");
    }
}</code>

In this updated code:

  • The IActionResult interface is implemented.
  • FileStreamResult is used to return the file.
  • Set the content type and filename for the downloaded file.

This method ensures that the HttpResponseMessage contains the correct content type and filename, allowing for seamless file downloads from your Web API.

The above is the detailed content of How to Return Files from an 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