使用web api输出图像HttpResponseMessage

时间:2012-10-21 19:53:19

标签: c# asp.net-web-api

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

2 个答案:

答案 0 :(得分:5)

以下内容:

  1. 确保路径正确(duh)

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

  3. 确保您打开信息流:

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

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

答案 1 :(得分:2)

您还可以使用StreamContent类来更有效地使用流来代替ByteArrayContent。

相关问题