访问特定于用户的本地化资源

时间:2016-07-02 13:06:25

标签: c# asp.net web-applications localization

我正在构建一个.NET Web App,其中本地化的字符串由Multilingual App Toolkit提供。它生成一个静态类,其属性具有资源文件中定义的名称。它看起来像这样:

/// <summary>
///   A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {

    private static global::System.Resources.ResourceManager resourceMan;

    private static global::System.Globalization.CultureInfo resourceCulture;

    [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
    internal Strings() {
    }

    /// <summary>
    ///   Returns the cached ResourceManager instance used by this class.
    /// </summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    internal static global::System.Resources.ResourceManager ResourceManager {
        get {
            if (object.ReferenceEquals(resourceMan, null)) {
                global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FaqBot.Resources.Strings", typeof(Strings).Assembly);
                resourceMan = temp;
            }
            return resourceMan;
        }
    }

    /// <summary>
    ///   Overrides the current thread's CurrentUICulture property for all
    ///   resource lookups using this strongly typed resource class.
    /// </summary>
    [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
    internal static global::System.Globalization.CultureInfo Culture {
        get {
            return resourceCulture;
        }
        set {
            resourceCulture = value;
        }
    }

    /// <summary>
    ///   Looks up a localized string similar to Good Morning.
    /// </summary>
    internal static string Greeting {
        get {
            return ResourceManager.GetString("Greeting", resourceCulture);
        }
    }

    /// <summary>
    ///   Looks up a localized string similar to Welcome.
    /// </summary>
    internal static string Welcome {
        get {
            return ResourceManager.GetString("Welcome", resourceCulture);
        }
    }
}

在我访问字符串的代码中,我可以设置文化,然后对字符串属性的后续访问返回正确本地化的字符串。

现在,我的Web App可以让用户选择他们的语言,我有一种存储这种偏好的机制。但是,由于Strings文件是静态的,如果一个用户更改了语言,则其他用户的后续字符串也会更改。 绕过这种方法的一种方法是在每次访问字符串之前明确设置文化,但这会导致竞争条件和丑陋的代码。

如果不在每次访问字符串之前明确设置文化,我怎样才能让每个用户以他们的首选语言获得回复?

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是创建一个新的HttpModule

public class LocalizationModule : IHttpModule
{
    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        // check if user is authenticated
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            var username = HttpContext.User.Identity.Name;
            /* 
               Your code to read user's culture name from the profile and
               put it in "lang" variable
            */
            var culture = new System.Globalization.CultureInfo(lang);
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
    }
}

并通过在web.config文件中注册它来运行它:

<configuration>
  <system.web>
    <httpModules>
      <add name="LocalizationModule " type="LocalizationModule"/> <!-- put the full namespace and class name in type attribute eg. MyApp.MyNamespace.LocalizationModule -->
     </httpModules>
  </system.web>
</configuration>