使用web api HttpResponseMessage输出图像

我正在尝试以下代码从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; } 

有小费吗?

作品:

  [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; } 

以下内容:

  1. 确保路径正确(duh)

  2. 确保您的路由正确。 您的Controller是ImageController,或者您已经定义了一个自定义路由以在其他控制器上支持“GetImage”。 (你应该得到404响应。)

  3. 确保您打开流:

    var stream = new FileStream(path, FileMode.Open);

我尝试了类似的东西,它对我有用。

您也可以使用StreamContent类来提高流的效率,而不是ByteArrayContent。