Home > Backend Development > C++ > How to Properly Return Files in ASP.NET Web API?

How to Properly Return Files in ASP.NET Web API?

Barbara Streisand
Release: 2025-01-18 17:41:09
Original
200 people have browsed it

How to Properly Return Files in ASP.NET Web API?

Correctly returns files in ASP.NET Web API

In ASP.NET MVC, returning files is very simple using the FileContentResult class. However, when using WebAPI, the approach is different.

Adapt to WebAPI

WebAPI uses different conventions and requires different return types. To adapt the Test method of a normal MVC controller to an API controller, we need to return IHttpActionResult instead of FileContentResult.

Initial attempts and problems

The initial attempt used the StreamContent class to return a file stream. Although the content type and length are set, only the header is shown in the browser.

Solution: ByteArrayContent

The problem is that StreamContent does not work with content that has already been read from the stream. Instead, we should use ByteArrayContent, which takes as input a byte array of a stream.

Modified code:

<code class="language-csharp">[HttpGet]
public HttpResponseMessage Generate()
{
    var stream = new MemoryStream();
    // 处理流。

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.ToArray())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CertificationCard.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}</code>
Copy after login

This modified code correctly returns the file content as the response, allowing downloading or display in the browser.

The above is the detailed content of How to Properly Return Files in ASP.NET 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