Home > Backend Development > C++ > How to Return a File Content Result from an ASP.NET Web API?

How to Return a File Content Result from an ASP.NET Web API?

Patricia Arquette
Release: 2025-01-18 17:26:09
Original
925 people have browsed it

How to Return a File Content Result from an ASP.NET Web API?

Returning File Content Results in ASP.NET Web API

While FileContentResult works well in MVC controllers for serving files like PDFs, directly porting this to an ApiController presents challenges. A simple attempt to use StreamContent often fails, resulting in JSON metadata instead of the file itself. The solution lies in leveraging ByteArrayContent.

This revised code snippet effectively returns a PDF file as a file content result from a Web API:

<code class="language-csharp">[HttpGet]
public HttpResponseMessage Generate()
{
    using (var stream = new MemoryStream())
    {
        // Process the stream to generate PDF content here...

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "CertificationCard.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }
}</code>
Copy after login

The key is using ByteArrayContent to encapsulate the file's bytes and setting the ContentDisposition header to "attachment" to prompt a download. The ContentType header ensures proper handling by the client. Note the use of using to ensure the MemoryStream is properly disposed. This approach enables seamless delivery of PDFs and other file types through your Web API.

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