Created
May 15, 2014 13:31
-
-
Save fisshy/1cbbf5f32469d460edec to your computer and use it in GitHub Desktop.
Simple Language module for Owin .NET C#
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 LanguageComponent | |
{ | |
App _next; | |
//sv-SE | |
string fallback = ConfigurationManager.AppSettings["language"]; | |
//sv-SE,en-EN etc | |
string[] accepted = ConfigurationManager.AppSettings["accepted-languages"].Split(','); | |
public LanguageComponent(App next) | |
{ | |
_next = next; | |
} | |
public async Task Invoke(IDictionary<string, object> environment) | |
{ | |
var cookies = environment["Microsoft.Owin.Cookies#dictionary"] as IDictionary<string, string>; | |
var language = string.Empty; | |
if (cookies.ContainsKey("_language")) | |
{ | |
language = cookies["_language"]; | |
} | |
else | |
{ | |
var headers = environment["owin.RequestHeaders"] as IDictionary<string, string[]>; | |
if (headers.ContainsKey("Accept-Language")) | |
{ | |
var languages = headers["Accept-Language"]; | |
var first = languages[0]; | |
language = first.Split(',')[0]; | |
} | |
var cookie = new HttpCookie("_language"); | |
cookie.Value = accepted.Contains(language) ? language : fallback; | |
HttpContext.Current.Response.Cookies.Add(cookie); | |
} | |
SetCulture(accepted.Contains(language) ? language : fallback); | |
await _next(environment); | |
} | |
public void SetCulture(string culture) | |
{ | |
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture); | |
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment