简体   繁体   中英

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:

 [HttpGet]
 public IActionResult GetImage()
 {
     return File("Image bytes", "image/jpeg");
 }

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.

Everything works fine, but is it the correct way of doing it?

The API returns the response that has FileContentResult . Is there a way to render that result without converting it to Base64 string and do what I am doing?

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.

Take your "uri" value and insert it into an image tag on your rendered page:

<img src="uri">

For example, if your uri is https://www.example.com/controller/getImage then you would end up with:

<img src="https://www.example.com/controller/getImage">

Then the browser will directly connect to your API server to pull the image.

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:

Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM