MVC Helper for Gravatar

Jus a quick code snippet for display a user’s Gravatar in MVC;

public static MvcHtmlString DisplayGravatar(this HtmlHelper helper,
            string emailAddress, int size=80)
            return new MvcHtmlString("<img src=" + 
                GravatarUrl(helper, emailAddress, size) + " />");

        public static string GravatarUrl(this HtmlHelper helper, 
            string emailAddress, int size=80)
            if (size < 1 || size > 512)
                size = 80;
            //1.Trim leading and trailing whitespace from an email address            
            //2.Force all characters to lower-case
            emailAddress = emailAddress.Trim().ToLower();
            //3.md5 hash the final string
            string md5Hash = GetMD5Hash(emailAddress);

            return string.Format("{0}?s={1}",
                                                            md5Hash, size);

        private static string GetMD5Hash(string input)
            System.Security.Cryptography.MD5CryptoServiceProvider x =
                new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            string password = s.ToString();
            return password;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s