从代码中自动更改语言

时间:2012-10-08 22:05:16

标签: asp.net

我在C#win应用程序中使用下面的代码来更改语言(例如changelanguge(“en”))如何在asp中使用这样的东西?

public void changelanguge(String languge)
        {
            foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
            {
                if (lang.Culture.TwoLetterISOLanguageName == languge)
                {
                    Application.CurrentCulture = lang.Culture;
                    Application.CurrentInputLanguage = lang;
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

选项1

在ASP.NET页面(ASPX)中,您需要覆盖InitializeCulture方法:

    protected override void InitializeCulture()
    {
        this.UICulture = "";
        this.Culture = "";
    }

选项2

在页面的标记中:

<%@ Page UICulture="" Culture=""

选项3

在web.config中

<globalization culture="" uiCulture="" enableClientBasedCulture="true" />

选项4

使用HttpModule(此示例使用ASP.NET配置文件获取语言,您可以更改以从其他来源获取语言)

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

    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += context_PreRequestHandlerExecute;
    }

    void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        var application = sender as HttpApplication;
        var context = application.Context;
        var handler = context.Handler;
        var profile = context.Profile as CustomProfile;

        if (handler != null)
        {
            var page = handler as Page;

            if (page != null)
            {
                if (profile != null)
                {
                    if (!string.IsNullOrEmpty(profile.Language))
                    {
                        page.UICulture = profile.Language;
                        page.Culture = profile.Language;
                    }
                }
            }
        }
    }
}

然后你只需要在web.config文件中配置它:

<httpModules>
  <add name="Localization" type="Msts.Topics.Chapter06___Globalization_and_Accessibility.Lesson01___Globalization_and_Localization.LocalizationModule" />
</httpModules>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="Localization" type="Msts.Topics.Chapter06___Globalization_and_Accessibility.Lesson01___Globalization_and_Localization.LocalizationModule" />
    </modules>
  </system.webServer>