Posted by Anuraj on Tuesday, July 11, 2017
This post is about creating a tag helper in ASP.NET Core for displaying Gravatar images based on the email address. Your Gravatar is an image that follows you from site to site appearing beside your name when you do things like comment or post on a blog.
Gravatar images may be requested just like a normal image, using an IMG tag. To get an image specific to a user, you must first calculate their email hash. All URLs on Gravatar are based on the use of the hashed value of an email address. Images and profiles are both accessed via the hash of an email, and it is considered the primary way of identifying an identity within the system. To ensure a consistent and accurate hash, the following steps should be taken to create a hash:
Here is the code.
This Tag Helper can be attached to an IMG tag. Code is simple and straight forward. First I am hashing the email address with MD5. Then I am converting the bytes to hexadecimal string using
BitConverter.ToString() method. The result string contains hypens, which we don’t require in Gravatar hash, so we are replacing it with empty string. And finally, I am converting everything into lower case.
You need to register the tag helper in the project using _ViewImports.cshtml file, like this.
Now you can use the Tag Helper in razor like this.
Which will render an image like this.
Happy Programming :)