【问题标题】:Get an image from a method with ActionResult as return type从以 ActionResult 作为返回类型的方法获取图像
【发布时间】:2023-03-25 10:20:01
【问题描述】:

我正在开发一个 Web Api 项目,并且正在从 MVC 项目中的控制器获取图像。返回类型为ActionResult。 Web Api 中的 GetImage 方法返回类型为HttpResponseMessage

public HttpResponseMessage GetImage() 
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    ActionResult image = GetProductImage();
    // ? result.Content = image;
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    return result;
}

有没有办法将图像从 ActionResult 放入 HttpResponseMessage 中? 另一个控制器中的代码如下所示(简化):

public ActionResult GetProductImage()
{
    byte[] bytes = GetImageFromDisk(fullImagePath);
    return File(bytes, "image/jpeg");
}

感谢您的帮助。

【问题讨论】:

  • 感谢您的提示,但我必须从另一个项目中调用 GetProductImage 方法。图像还有很多事情要做(裁剪图像、缓存、水印......)。我不想重写所有内容。真的没有办法从 ActionResult 中取出图像吗?

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


【解决方案1】:
public HttpResponseMessage Image(int pIndice)
{    
    var response = new HttpResponseMessage(HttpStatusCode.OK);

    using (var binaryReader = new BinaryReader(requestFile[pIndice].InputStream))
    {
        response.Content = new ByteArrayContent(binaryReader.ReadBytes(requestFile[pIndice].ContentLength));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(requestFile[pIndice].ContentType ?? "image/jpeg");
    }
    return response; 
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。此外,您应该尝试更好地格式化您的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多