29

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

2 回答 2

5

以下内容:

  1. 确保路径正确(呃)

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

  3. 确保打开流:

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

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

于 2012-12-18T15:47:10.977 回答
2

除了 ByteArrayContent,您还可以使用 StreamContent 类来更有效地处理流。

于 2013-10-19T19:38:01.920 回答