[英]Is it correct way of displaying Image from .NET Core API in ASP.NET MVC View?
I have a .NET Core API that returns an image:我有一个返回图像的 .NET Core API:
[HttpGet]
public IActionResult GetImage()
{
return File("Image bytes", "image/jpeg");
}
Controller: Controller:
public async Task<IActionResult> Index()
{
using var client = new HttpClient();
var response = await client.GetAsync("uri");
var bytes = await response.Content.ReadAsByteArrayAsync();
var base64 = Convert.ToBase64String(bytes);
var imgSrc = string.Format("data:image/jpeg;base64,{0}", base64);
var model = new ImageData { ImageSrc = imgSrc };
return View(model);
}
And in the view, I just pass the image source to img
element.在视图中,我只是将图像源传递给
img
元素。
Everything works fine, but is it the correct way of doing it?一切正常,但这是正确的做法吗?
The API returns the response that has FileContentResult
. API 返回具有
FileContentResult
的响应。 Is there a way to render that result without converting it to Base64 string and do what I am doing?有没有办法在不将其转换为 Base64 字符串的情况下呈现该结果并执行我正在做的事情?
Appreciate any comments.感谢任何评论。
Your API code is simply returning an image as any other web server would (from the client's perspective), so unless there's some authentication step that you haven't shown, you should be able to simply use the endpoint URL directly in an img
tag.您的 API 代码只是返回图像,就像任何其他 web 服务器一样(从客户端的角度来看),所以除非有一些您没有显示的身份验证步骤,否则您应该能够直接使用端点
img
和 im8B4D45903DZ
Take your "uri"
value and insert it into an image tag on your rendered page:获取您的
"uri"
值并将其插入到渲染页面上的图像标签中:
<img src="uri">
For example, if your uri is https://www.example.com/controller/getImage then you would end up with:例如,如果您的 uri 是https://www.example.com/controller/getImage那么您最终会得到:
<img src="https://www.example.com/controller/getImage">
Then the browser will directly connect to your API server to pull the image.然后浏览器会直接连接到你的API服务器来拉取图片。
Incidentally, if you're just trying to serve local files from your ASP.NET Core API, you might be interested in using the built-in static file functionality instead:顺便说一句,如果您只是想从 ASP.NET 内核 API 提供本地文件,您可能会对使用内置的static 文件功能感兴趣:
Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.