Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-01 09:20:02
Original
207 people have browsed it

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

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!

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!