Skip to content

Instantly share code, notes, and snippets.

@azcoov
Created January 24, 2011 05:34
Show Gist options
  • Save azcoov/792877 to your computer and use it in GitHub Desktop.
Save azcoov/792877 to your computer and use it in GitHub Desktop.
UrlExtension to render Gravatars
using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;
public static class GravatarExtension
{
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();
}
}
@azcoov
Copy link
Author

azcoov commented Jan 24, 2011

To implement this from a view:

<img alt="Gravatar" src="<%= Url.Gravatar(EmailAddress,40) %>" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment