ASP.NET MVC Gravatar Helpers

Gravatar is a service that provides globally unique avatars linked to email addresses. Imagine you could include a user's gravatar in a view simply by passing their email address to a helper:

<img src="<%= Url.Gravatar("user@domain.com") %>" />

All we need to do is to add some extension methods to UrlHelper to generate the url to the gravatar service:

    public static class UrlExtensions
    {
        public static string Gravatar(this UrlHelper url, string emailAddress)
        {
            var baseUrl = "http://www.gravatar.com/avatar/{0}";
            return String.Format(baseUrl, MD5Hash(emailAddress.ToLower()));
        }

        public static string Gravatar(this UrlHelper url, string emailAddress, int size)
        {
            var baseUrl = "http://www.gravatar.com/avatar/{0}?s={1}";
            return String.Format(baseUrl, MD5Hash(emailAddress.ToLower()), size);
        }

        private static string MD5Hash(string input)
        {
            StringBuilder hash = new StringBuilder();
            MD5CryptoServiceProvider md5provider = new MD5CryptoServiceProvider();
            byte[] bytes = md5provider.ComputeHash(new UTF8Encoding().GetBytes(input));

            for (int i = 0; i < bytes.Length; i++)
            {
                hash.Append(bytes[i].ToString("x2"));
            }
            return hash.ToString();
        }
    }

 The second overload of the Gravatar() method accepts a parameter called 'size' that is the desired size of the gravatar in pixels. The default is 80.

 


Comments

Comments are closed