Gravatar C# API

Subscribe to my newsletter and never miss my upcoming articles

Introduction

Several years ago, around 2015, I needed a way to get some basic profile information for users in an app I did. I decided to use Gravatar because they let you get some basic user information if you just pass them an email address.

The library is pretty simple, it just uses a HttpClient to call Gravatar and translate the response into a C# object. Back then I (and many other developers) mistakenly thought that HttpClient was supposed to be disposed after each usage mainly because it exposes the IDisposable interface and as a good .net developer you have learned to always dispose your resources when you no longer need them, more on that in this Visual Studio Magazine article.

So, now it's 2021 and I wanted to use the API in a new Azure Function (a post on that coming up shortly) and of course wanted to update the API to use HttpClient correctly. Thus I made an update to it.

The Gravatar C# API

I have put the code in this public Github repository. I have also published the library as a Nuget for you to include in your projects:

Install-Package GravatarSharp.Core -Version 0.9.0.2

Implementation

There are 2 features in the library; getting the user profiel and getting the profile image.

Get Image Url from Gravatar

Here is how to get the image url for a given email:

/// <summary>
///     Gets the Gravatar image url for the given user/email
/// </summary>
/// <param name="email">The email that will be used to request the user image url</param>
/// <param name="width">The width in pixels. Default is 128</param>
/// <returns>The image url corresponding to the provided email address</returns>
public static string GetImageUrl(string email, int width = 128)
{
    return $"http://www.gravatar.com/avatar/{Hashing.CalculateMd5Hash(email)}?s={width}&d=identicon&r=PG";
}

As you might have noticed, this is hashing the email, because that is what Gravatar accepts, this is done like so:

/// <summary>
///     Calculate the hash based on this MSDN post:
///     http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
/// </summary>
/// <param name="input">The input to hash</param>
/// <returns>The hashed and lowered string</returns>
public static string CalculateMd5Hash(string input)
{
    // step 1, calculate MD5 hash from input
    var md5 = MD5.Create();
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hash = md5.ComputeHash(inputBytes);

    // step 2, convert byte array to hex string
    var sb = new StringBuilder();
    foreach (var t in hash) sb.Append(t.ToString("X2"));
    return sb.ToString().ToLower();
}

Get User Profile from Gravatar

The second feature is to get the user info that Gravatar has on a given email:

/// <summary>
/// Gets the Gravatar profile for the given user/email
/// </summary>
/// <param name="email">The email that will be used to request the user profile</param>
/// <returns>The user profile corresponding to the provided email address</returns>
public async Task<GetProfileResult> GetProfile(string email)
{
    var json = await GetStringResponse($"https://en.gravatar.com/{Hashing.CalculateMd5Hash(email)}.json");
    if (string.IsNullOrEmpty(json.ErrorMessage))
        return new GetProfileResult
        {
            Profile = new GravatarProfile(JsonConvert.DeserializeObject<Profile>(json.Result), json.Result)
        };
    return new GetProfileResult
    {
        ErrorMessage = json.ErrorMessage
    };
}

Here we just append .json to the request url and then Gravatar will return a JSON file which the library then translate into a C# object for you to use.

Remember, you can see the full source code of this library:

Thanks for reading, please let me know if you find this useful or if you have any other feedback. I would love to get your comments!

Also, stay tunes, I will soon post an article on how to use this library in an Azure Function especially how to use dependency injection to inject the HttpClient.

No Comments Yet