Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 534
rtcardoso Avatar asked Oct 10 '22 16:10

rtcardoso


1 Answers

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";
}
like image 59
Waqas Raja Avatar answered Oct 13 '22 09:10

Waqas Raja