【问题标题】:output image using web api HttpResponseMessage使用 web api HttpResponseMessage 输出图像
【发布时间】:2012-10-21 19:53:19
【问题描述】:

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

【问题讨论】:

  • 不太确定我是否得到了你 - 但你可以查看how to write an image to outputStream
  • 我没有收到错误,我什么也没收到。
  • 你返回什么状态码?
  • 我知道这是一篇旧帖子,但您应该更新您的示例以正确处理,仅适用于可能出现并复制/粘贴到他们的应用程序中的新手。
  • 我们如何使用端点在 .net 核心网络应用程序上显示图像?在浏览器上,它似乎只需要端点本身来加载图像。

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


【解决方案1】:

以下内容:

  1. 确保路径正确(duh)

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

  3. 确保打开流:

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

我尝试了类似的方法,它对我有用。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2015-02-21
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      相关资源
      最近更新 更多