【问题标题】:How to dynamically initialize Culture in ASP.NET WebService Call?如何在 ASP.NET WebService 调用中动态初始化文化?
【发布时间】:2011-10-25 17:11:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net web-services currentculture


    【解决方案1】:

    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 方法中将不可用,您可以在您的 web 方法中执行此操作。

    [WebMethod]
    public static string MyWebMethod()
    {
        String culture = Session["MyCurrentCulutre"] as String;
    
        System.Threading.Thread.CurrentThread.CurrentCulture = 
           System.Globalization.CultureInfo.CreateSpecificCulture(culture);
    
        return "My results";
    }
    

    【讨论】:

    • InitializeCulture() 是一种页面方法而不是 System.Web.Services.WebService 方法。
    • @Waqas Raja,你能从现实生活中免费举一个例子,为什么我每个人都想这样做?假设我来自以色列,而 iis 在我们身上……你能举个例子吗?
    • 想象一下我在会话中保存了首选的用户语言。然后我的 javascript 进行网络服务调用。在回复中,我想以用户首选语言发送用户消息...
    • @WaqasRaja 你说的是真的,但是选择的语言的值是在Session State,在Application_BeginRequest session 还没有加载。
    • 这是我的解决方案,但我试图避免在我创建的每个网络方法中都这样做。
    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2015-05-06
    • 1970-01-01
    • 2011-01-03
    • 2019-10-03
    相关资源
    最近更新 更多