Returning a PDF File from an ASP.NET Web API
In standard MVC controllers, returning a PDF using FileContentResult
is simple. However, ApiController
requires a different approach.
The Problem
Using the typical IHttpActionResult
return type in ApiController
presents challenges when returning a PDF. Simply returning a StreamContent
, as some examples suggest, often results in the browser displaying headers instead of the PDF file itself.
The Correct Method
The key is to use ByteArrayContent
instead of StreamContent
. This converts the stream data into a byte array for proper transmission. Here's an improved example:
<code class="language-csharp">[HttpGet] public HttpResponseMessage Generate() { MemoryStream stream = new MemoryStream(); // ... PDF generation code to populate the stream ... HttpResponseMessage 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>
This code uses ByteArrayContent
to send the PDF as a byte array. Crucially, it sets the ContentDisposition
header to attachment
(telling the browser to download the file) and the ContentType
to application/octet-stream
(indicating a binary file). This ensures the PDF is correctly downloaded instead of being rendered in the browser.
The above is the detailed content of How to Return a FileContentResult (PDF) from an ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!