将 IRestResponse 转换为"image/jpg"文件



我正在尝试从 API 中提取图像并通过File()方法返回到 DOM。

这是我到目前为止所拥有的..

HomeController.cs

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ImageFromPath()
{
var client = new RestClient("http://{{MYIPADDRESS}}/cgi-bin/snapshot.cgi?channel0=");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "random-postman-token");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Digest username="MYUSERNAME", realm="MYENCRYPTEDPASS", nonce="LONGSTRING", uri="/cgi-bin/snapshot.cgi?channel0", response="RESPONSESTRING", opaque=""");
IRestResponse response = client.Execute(request);(response.RawBytes);
return File(response, "image/jpg");
}
}

这里唯一的问题是 return 语句上的错误,response显示

无法从"RestSharp.IRestResponse"转换为"byte[]">


当我从本地文件系统中提取图像时,它更容易且有效,这是我的工作代码HomeController.cs

public ActionResult ImageFromPath(string path)
{
var ms = new MemoryStream();
using (Bitmap bitmap = new Bitmap(path))
{
var height = bitmap.Size.Height;
var width = bitmap.Size.Width;
bitmap.Save(ms, ImageFormat.Jpeg);
}
ms.Position = 0;
return File(ms, "image/jpg");
}

这是我如何在前端(Index.cshtml(中拉动它的方式:

<img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />

这里这一行:

return File(response, "image/jpg");

您正在将其传递response类型为IRestResponse(来自RestSharp的类型(。

为什么内置的MVC文件方法会知道RestSharp?File()采用字节数组和字符串 MIME 类型。

尝试:

return File(response.RawBytes, "image/jpg");

RawBytes是来自 HTTP 请求的原始响应的字节数组。 如果您的 API 返回图像的字节数组,则需要将其传递给 file 方法。

最新更新