5

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.

rtcardoso
  • 111
  • 2
  • 8

1 Answers1

5

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";
}
Waqas Raja
  • 10,802
  • 4
  • 33
  • 38
  • InitializeCulture() is a Page Method not a System.Web.Services.WebService method. – rtcardoso Oct 25 '11 at 17:17
  • 1
    @Waqas Raja , Can you give a free exmple from real life why would i every want to do that ? lets say im from israel and the iis is in us...can you give example ? – Royi Namir Oct 25 '11 at 17:18
  • Imagine that i save the preferred user language in session. Then my javascript makes a webservice call. In the response i want to to send a user message in user preferred language... – rtcardoso Oct 25 '11 at 17:25
  • @WaqasRaja What you say is true, but the value of the selected language is in Session State, and in Application_BeginRequest session is not loaded yet. – rtcardoso Oct 25 '11 at 17:34
  • 1
    That is my solution, but i'm trying to avoid doing this in every webmethod i create. – rtcardoso Oct 25 '11 at 17:37
  • @WRCardoso Global.asax is also there for you; have a look on my updated answer. – Waqas Raja Oct 25 '11 at 17:37
  • @WRCardoso `PreRequestHandlerExecute` event is also there in `Global.asax`. Have a try. – Waqas Raja Oct 25 '11 at 17:55