Skip to content

Instantly share code, notes, and snippets.

@veggerby
Created July 5, 2011 08:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veggerby/1064440 to your computer and use it in GitHub Desktop.
Save veggerby/1064440 to your computer and use it in GitHub Desktop.
Get gravatar URL from Email
public static string GravatarUrl(this UrlHelper url, string email, int size)
{
string imageUrl = ConfigurationManager.AppSettings["DefaultGravatar"]; // e.g. "identicon" or a URL to image
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);
}
public static Uri GetBaseUrl(this UrlHelper url)
{
Uri contextUri = new Uri(url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
public static string Absolute(this UrlHelper url, string contentUrl)
{
return new Uri(GetBaseUrl(url), url.Content(contentUrl)).AbsoluteUri;
}
public static string MD5(this string value)
{
System.Security.Cryptography.MD5 algorithm =
System.Security.Cryptography.MD5.Create();
byte[] data = Encoding.ASCII.GetBytes(value);
data = algorithm.ComputeHash(data);
string md5 = "";
for (int i = 0; i < data.Length; i++)
{
md5 += data[i].ToString("x2").ToLower();
}
return md5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment