Last active
January 22, 2017 18:28
-
-
Save cecilphillip/2f597609541f430fb486b0052ab45ecf to your computer and use it in GitHub Desktop.
ASP.NET Web API Media-Type Formatter for Gravatar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Customer | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
public String Email { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GravatarFormatter : MediaTypeFormatter | |
{ | |
private const string GRAVATAR_TEMPLATE = "https://www.gravatar.com/avatar/{0}"; | |
public GravatarFormatter() | |
{ | |
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png")); | |
} | |
public override bool CanReadType(Type type) | |
{ | |
return false; | |
} | |
public override bool CanWriteType(Type type) | |
{ | |
return type == typeof(Customer); | |
} | |
public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) | |
{ | |
var customer = value as Customer; | |
if (customer != null) | |
{ | |
var email = customer.Email; | |
string hashedEmail = string.Empty; | |
using (var md5haser = MD5.Create()) | |
{ | |
var byteHash = md5haser.ComputeHash(Encoding.UTF8.GetBytes(email)); | |
var builder = new StringBuilder(); | |
for (int i = 0; i < byteHash.Length; i++) | |
{ | |
builder.Append(byteHash[i].ToString("x2")); | |
} | |
hashedEmail = builder.ToString(); | |
} | |
var gravatarUrl = string.Format(GRAVATAR_TEMPLATE, hashedEmail); | |
var client = new HttpClient(); | |
var responseBytes = await client.GetByteArrayAsync(gravatarUrl); | |
await writeStream.WriteAsync(responseBytes, 0, responseBytes.Length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment