Posts
60
Comments
36
Trackbacks
18
Integrating Gravatar Into Your ASP.Net MVC Application

Naturally, whenever I try to overcomplicate things; I turn around and blog about them.  This will be short and sweet as adding a Gravatar to your site that is dynamically generated is actually fairly simple.  I always try to oversimplify too, but there were a few small snags I ran into while doing this.

  • You need to have your users email address (or hash) available to your .aspx
  • I use a string extension, so that I can call VarName.ToMd5()

Ok, so Gravatar is cool.  I ran across it for the first time about 20 minutes ago, and wow is it surprisingly easy, though there are a few minor complications I ran into.  Here is my story.

First, you will need a static class for your static extension.  Note, this MD5 was taken straight from an MSDN Library.  You must first lowercase the email address you are hashing.  Additionally, you will also need to .ToLowerCase() the MD5 string in the return line (This is for URL Case Sensitive request to Gravatar.com).  These were my most interesting issues while trying to match the hash for the Gravatar.  Code:

        /// <summary>
        /// Displays the Gravatar MD5 hash of the given string.
        /// </summary>
        /// <returns>MD5 Representation of this string</returns>
        public static string ToMd5(this string helper)
        {
            helper = helper.ToLower();
 
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(helper);
            byte[] hash = md5.ComputeHash(inputBytes);
 
            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString().ToLower();
        }

To implement in your page (assuming your STATIC extension class/method(above) are reachable from your ASP.NET MVC Page or class, call this method using something similar to:

<img src="http://www.gravatar.com/avatar/<%= VarName.Email.ToMd5() %>.jpg" />

I certainly hope your endeavor in adding this web service was as pleasurable as mine.  Enjoy.

Technorati Tags: ,,,,
posted on Sunday, April 26, 2009 1:10 AM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 1 and 3 and type the answer here:
News
My Developer Notebook! This also happens to be my opinion place. Thanks for coming by.