Image Tag Helper In ASP.NET CORE MVC
In this tutorial we will discuss and understand about the image tag helper fin ASP.NET Core MVC
This topic is very important if your application requires it to display images. So let’s start understand the why require the image tag helpers
So before jumping let’s understand the concept of browser caching and will see how he relates to the image tag helpers
Browser Caching
In general, when you visit a web page and if that web page contains some image, then most of the modern web browser cache the images for later use. In the future, when you revisit to that web page, then the browser loads the images from cache instead of downloading the images from the server.
Disable Browser Caching
If you want then you can also disable the browser cache. Once you disable the browser cache then it will not cache the images and each and every time it will download the images from the server when you visit the page. disable browser cache in Google Chrome Press F12 key to launch the Browser Developer Tools. Then click on the “Network” tab and check then “Disable Cache” checkbox.
Use of Image Tag Helper.
If you disable the browser cache, then each and every time it will download the image from the server. If you didn’t disable the browser cache, then it will serve the image from the browser cache. But the problem with this approach is that, if you changed the image,then you will not get the updated image.
To overcome the above problems, i.e. download the image from the server only when it has changed else serve the image from the browser cache, we need to use the Image Tag helper in ASP.NET Core MVC Application.
Configure Image Tag Helper.
In order to use the Image Tag Helper in ASP.NET Core Application, you need to add the asp-append-version attribute to the tag and need to set the value to true as shown below.
Configure image tag helper globally import below into _viewimports.cshtml file.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
When we run our application after this changes you will find image tag helper appended some unique value that know as unique hash value
The ASP.NET Core Image Tag Helper enhances the tag to provide cache-busting behavior for the static image files. That means based on the content of the image, a unique hash value is calculated and then appended to image URL as you can see in the above image. This unique hash value decides whether to load the image from the server or to load the image from the browser cache. If the hash value changes then it will reload the image from the server else it will reload the image from the cache.
Now if you remains some images into server as below . In below we have renamed the new image old image name.
After this changes img tag still loading image from browser cache but image tag helper images are loading from server as its changed
You can watch our video version of this tutorial with step by step explanation.