如何在ASP.NET WebService调用中动态初始化文化?

时间:2011-10-25 17:11:44

标签: asp.net web-services currentculture

有谁能告诉我如何在asp.net webservice调用中动态初始化线程文化?

在我的aspx页面中,我有一个基页,我覆盖了InitializeCulture()方法。

请注意,所选语言的值保存在会话状态中。

1 个答案:

答案 0 :(得分:4)

Global.asax文件中,您可以设置当前的文化,即使是其网络服务或网页。

// PreRequestHandlerExecute occurs after initialization of Session
void Application_PreRequestHandlerExecute(Object Sender, EventArgs e)
{
    // check if session is required for the request
    // as .css don't require session and accessing session will throw exception
    if (Context.Handler is IRequiresSessionState
        || Context.Handler is IReadOnlySessionState)
    {
        string culture = "en-US";
        if (Session["MyCurrentCulutre"] != null)
        {
            culture = Session["MyCurrentCulutre"] as String;
        }

        System.Threading.Thread.CurrentThread.CurrentCulture = 
           System.Globalization.CultureInfo.CreateSpecificCulture(culture);
    }
}

您正在更改自己的要求,但Session方法无法使用Begin_Request对象,您可以在网络方法中执行此操作。

[WebMethod]
public static string MyWebMethod()
{
    String culture = Session["MyCurrentCulutre"] as String;

    System.Threading.Thread.CurrentThread.CurrentCulture = 
       System.Globalization.CultureInfo.CreateSpecificCulture(culture);

    return "My results";
}