从 ASP.NET Web API 中的控制器返回二进制文件 [英] Returning binary file from controller in ASP.NET Web API
问题描述
我正在使用 ASP.NET MVC 的新 WebAPI 开发 Web 服务,该服务将提供二进制文件,主要是 .cab
和 .exe
文件.
I'm working on a web service using ASP.NET MVC's new WebAPI that will serve up binary files, mostly .cab
and .exe
files.
以下控制器方法似乎有效,这意味着它返回一个文件,但它将内容类型设置为 application/json
:
The following controller method seems to work, meaning that it returns a file, but it's setting the content type to application/json
:
public HttpResponseMessage<Stream> Post(string version, string environment, string filetype)
{
var path = @"C:Temp est.exe";
var stream = new FileStream(path, FileMode.Open);
return new HttpResponseMessage<Stream>(stream, new MediaTypeHeaderValue("application/octet-stream"));
}
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
尝试使用简单的 HttpResponseMessage
,其 Content
属性设置为 StreamContent
:
Try using a simple HttpResponseMessage
with its Content
property set to a StreamContent
:
// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;
public HttpResponseMessage Post(string version, string environment,
string filetype)
{
var path = @"C:Temp est.exe";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
关于使用的 stream
的一些注意事项:
A few things to note about the stream
used:
你不能调用
stream.Dispose()
,因为Web API在处理控制器方法的result
发送时仍然需要能够访问它数据返回给客户端.因此,不要使用using (var stream = …)
块.Web API 将为您处理流.
You must not call
stream.Dispose()
, since Web API still needs to be able to access it when it processes the controller method'sresult
to send data back to the client. Therefore, do not use ausing (var stream = …)
block. Web API will dispose the stream for you.
确保流的当前位置设置为 0(即流数据的开头).在上面的示例中,这是给定的,因为您刚刚打开了文件.但是,在其他情况下(例如当您第一次将一些二进制数据写入 MemoryStream
时),请确保 stream.Seek(0, SeekOrigin.Begin);
或设置stream.Position = 0;
Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream
), make sure to stream.Seek(0, SeekOrigin.Begin);
or set stream.Position = 0;
对于文件流,明确指定FileAccess.Read
权限有助于防止 Web 服务器上的访问权限问题;IIS 应用程序池帐户通常只被授予对 wwwroot 的读取/列出/执行访问权限.
With file streams, explicitly specifying FileAccess.Read
permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.
这篇关于从 ASP.NET Web API 中的控制器返回二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!