Last active
December 22, 2015 11:09
-
-
Save janhebnes/6463709 to your computer and use it in GitHub Desktop.
Parsing Web Browser Languages can be a pain here are some code snippets we use for getting the actual browser languages
This file contains hidden or 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
// Try to match the local date format of the browser | |
var userLanguages = LanguageItem.GetRequestUserLanguages(); | |
// Ignore if no language preferences | |
if (userLanguages != null) | |
{ | |
var culture = CultureInfo.CreateSpecificCulture(userLanguages.First().IsoCode); | |
return Updated.ToString("d", culture); | |
} | |
return Updated.ToString("dd.MM.yyyy"); | |
/// <summary> | |
/// UserLanguages in User Browser Request. | |
/// </summary> | |
/// <returns>Parsed Browser User Languages ordered by Weight</returns> | |
public static IEnumerable<UserLanguage> GetRequestUserLanguages() | |
{ | |
if (HttpContext.Current == null) return null; | |
if (HttpContext.Current.Request.UserLanguages == null) return null; | |
return HttpContext.Current.Request.UserLanguages.Select( | |
d => new UserLanguage { IsoCode = ParseUserLanguage(d), Weight = ParseUserLanguageWeight(d) }). | |
OrderByDescending(l => l.Weight); | |
} | |
/// <summary> | |
/// Parse the language part of the userlanguage element | |
/// </summary> | |
/// <example> | |
/// E.g. UserLanguages en-US / en;q=0.8 / da;q=0.6 / de;q=0.4 / de-DE;q=0.2 / de-CH;q=0.2 | |
/// </example> | |
/// <param name="s">userLanguage element</param> | |
/// <returns>IsoCode</returns> | |
private static string ParseUserLanguage(string s) | |
{ | |
return !s.Contains(";q=") ? s : s.Substring(0, s.IndexOf(";q=")); | |
} | |
/// <summary> | |
/// Find the weight of the userlanguage | |
/// </summary> | |
/// <example> | |
/// E.g. UserLanguages en-US / en;q=0.8 / da;q=0.6 / de;q=0.4 / de-DE;q=0.2 / de-CH;q=0.2 | |
/// </example> | |
/// <remarks>comes with a potential ";q=0.8" of none is specified it is assumed as 1 </remarks> | |
/// <param name="s">userLanguage element</param> | |
/// <returns>the weight / priority from 1 to 0</returns> | |
private static double ParseUserLanguageWeight(string s) | |
{ | |
if (!s.Contains(";q=")) | |
{ | |
return 10; | |
} | |
double o; | |
var q = s.Substring(s.IndexOf(";q=") + 3); | |
return double.TryParse(q, out o) ? o : 10; | |
} | |
public class UserLanguage | |
{ | |
public string IsoCode | |
{ | |
get; set; | |
} | |
public double Weight | |
{ | |
get; set; | |
} | |
#endregion Properties | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment