How do i get user Culture in a HtmlHelper extension for MVC 3 .NET Application?
I'm creating a new HtmlHelper exte开发者_开发技巧nsion for my MVC 3 Application. I need to get the Culture Info of the user viewing the page inside my new helper.
How can i get it??
public static class HtmlExtension
{
public static string StringFor(this HtmlHelper html, string key)
{
...
//I need to get CultureInfo in here!
...
}
}
The direct answer is "grab it through CultureInfo.CurrentCulture
", but by itself it won't help you.
Consider that your application has no notion of the "user's culture" -- the user talks to you through their browser, you are not on their system.
Now the browser does give you an Accept-Language
header you can work with (Google will give you many hits), but it's not recommended to use this setting to determine the user's locale because in practice hardly any users know about this setting and have customized it to reflect their preference.
The best approach is probably to unilaterally decide what the user's culture is (e.g. have en
as a default, and give them a way to change it through the UI), store it somewhere (either inside session state or as a route variable) and push it into CultureInfo.CurrentCulture
inside HttpApplication.AcquireRequestState
. You can do this inside Global.asax
(example taken from MSDN):
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
CultureInfo ci = (CultureInfo)this.Session["culture"];
if (ci != null) {
CurrentThread.CurrentUICulture = ci;
CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
At this point, this answer becomes a self-fulfilling prophecy and you can access the culture through CultureInfo.CurrentCulture
from anywhere.
精彩评论