我正在尝试以下代码从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;
}
任何提示?
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;
}
答案 0 :(得分:5)
以下内容:
确保路径正确(duh)
确保您的路由正确无误。您的Controller是ImageController,或者您已经定义了一个自定义路由以支持其他控制器上的“GetImage”。 (你应该得到404响应。)
确保您打开信息流:
var stream = new FileStream(path, FileMode.Open);
我尝试了类似的东西,它对我有用。
答案 1 :(得分:2)
您还可以使用StreamContent类来更有效地使用流来代替ByteArrayContent。