简体   繁体   English

如何在包装器 class 中获取当前的 CultureInfo?

[英]How get current CultureInfo in wrapper class?

I have Main.Master page with buttons that set CultureInfo and store it in session:我有 Main.Master 页面,其中包含设置 CultureInfo 并将其存储在 session 中的按钮:

protected void RU_Click(object sender, ImageClickEventArgs e)
{
    Session["MyCulture"] = CultureInfo.CreateSpecificCulture("ru-Ru");
    Server.Transfer(Request.Url.LocalPath);     
}

protected void USA_Click(object sender, ImageClickEventArgs e)
{
    Session["MyCulture"] = CultureInfo.CreateSpecificCulture("en-AU");
    Server.Transfer(Request.Url.LocalPath);  
}

I write I non page behind wrapper class and in this class I need to get this Culture from session.我在包装器 class 后面写了我的非页面,在此 class 中,我需要从 session 获取此文化。 How can I get it?我怎么才能得到它?

The best thing to do when working with Culture and localization information is to set it to where they belong: on the current thread.处理文化和本地化信息时最好的做法是将其设置到它们所属的位置:在当前线程上。 Try this:尝试这个:

System.Threading.Thread.CurrentThread.CurrentCulture = yourCulture;

This way you can always get the current culture from the thread your request is running on.这样,您始终可以从运行您的请求的线程中获取当前文化。 You may also consider setting CurrentUICulture as well as some of the localization mechanism use that value.您还可以考虑设置 CurrentUICulture 以及一些本地化机制使用该值。

To follow your current approach if you just want to access a session variable in a class that doesnt inherit from System.Web.UI.Page you can simply access it like this.如果您只想访问不从 System.Web.UI.Page 继承的 class 中的 session 变量,请遵循您当前的方法,您可以像这样简单地访问它。

return (CultureInfo)HttpContext.Current.Session["MyCulture"];

I'm making the assumption that you added a seperate class.我假设您添加了单独的 class。

If you have a web project you could try to integrate this in your Global.asax and have your wrapper class wrap the Global.asax properties too.如果您有 web 项目,则可以尝试将其集成到 Global.asax 中,并让包装器 class 也包装 Global.asax 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM