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>
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!