ASP.NET MVC Gravatar HtmlHelper

Here is a quick little URL Helper extension method to add Gravatar images/photos/avatars to your page:

public static string GravatarUrl(this UrlHelper url, string email, int size)
{
    string imageUrl = ConfigurationManager.AppSettings["DefaultGravatar"];
    if (imageUrl.StartsWith("~/"))
    {
        imageUrl = url.Absolute(imageUrl);
    }

    if (string.IsNullOrEmpty(email))
    {
        return imageUrl;
    }

    string md5 = email.ToLowerInvariant().MD5();
    return string.Format(
        "http://www.gravatar.com/avatar/{0}.jpg?d={1}&s={2}&r=g",
        md5.ToLowerInvariant(),
        url.Encode(imageUrl),
        size);
}

public static string GravatarUrl(this UrlHelper url, string email)
{
    return url.GravatarUrl(email, 32);
}

It uses another custom URL Helper extension method Absolute to generate an absolute URL to a default image (based on an application relative url).

The Absolute extension method is similar to the ActionAbsolute method I posted earlier:

public static string Absolute(this UrlHelper url, string contentUrl)
{
    return new Uri(GetBaseUrl(url), url.Content(contentUrl))
        .AbsoluteUri;
}

And it also used the MD5 extension method from yesterdays post.


Follow

Get every new post delivered to your Inbox.