C# 使用 web api HttpResponseMessage 输出图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13001588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
output image using web api HttpResponseMessage
提问by lolol
I'm trying the following code to output a image from a asp.net web api, but the response body length is always 0.
我正在尝试使用以下代码从 asp.net web api 输出图像,但响应正文长度始终为 0。
public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream(@"path to image"));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
Any tips?
有小费吗?
WORKS:
作品:
[HttpGet]
public HttpResponseMessage Resize(string source, int width, int height)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
// Photo.Resize is a static method to resize the image
Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
采纳答案by Daniel Miller
The the following:
以下内容:
Ensure path is correct (duh)
Ensure your routing is correct. Either your Controller is ImageController or you have defined a custom route to support "GetImage" on some other controller. (You should get a 404 response for this.)
Ensure you open the stream:
var stream = new FileStream(path, FileMode.Open);
确保路径正确(废话)
确保您的路由正确。您的控制器是 ImageController 或者您已经定义了一个自定义路由来支持其他控制器上的“GetImage”。(您应该会收到 404 响应。)
确保您打开流:
var stream = new FileStream(path, FileMode.Open);
I tried something similar and it works for me.
我尝试了类似的东西,它对我有用。
回答by Gertjan
Instead of a ByteArrayContent you can also use a StreamContent class to work more efficient with streams.
除了 ByteArrayContent,您还可以使用 StreamContent 类来更有效地处理流。

