How to dynamically initialize Culture in ASP.NET WebService Call?

5.7k views Asked by At

Can anyone tell me how can i dynamically initialize thread culture in a asp.net webservice call?

In my aspx pages i have a base page where i override the InitializeCulture() Method.

Note that the value of selected language is saved in Session State.

1

There are 1 answers

7
Waqas Raja On

In Global.asax file you can set the current culture, even if its web service or web page.

// 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);
    }
}

You are changing your requirements, however Session object will not be available in Begin_Request method, you can do this in your web method.

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

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

    return "My results";
}