"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-03-22
Browse:412

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:

[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;
    }
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3