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