Asp.Net 核心中的本地化

Localization in Asp.Net Core

我一直按照此页面上的说明设置本地化:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization

然而,对我来说它似乎不起作用。这是我所做的:

Startup.cs:

public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", true, true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(o => o.ResourcesPath = "Resources");
        services.AddMvc(o =>
        {
            o.Filters.Add(typeof(GlobalExceptionFilter));
        }
        ).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var supportedCultures = new[]
        {
            new CultureInfo("es-MX"),
            new CultureInfo("en-US")
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("es-MX"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseMvcWithDefaultRoute();
        //app.UseMvc(routes =>
        //{
        //    routes.MapRoute(
        //        "default", "{controller=Home}/{action=Index}/{id?}");
        //});

        app.UseRewriter(new RewriteOptions().AddRedirectToHttps());
    }
}

我的 Layout.cshtml 包含以下内容:

@await Html.PartialAsync("_SelectLanguagePartial")

我的 _SelectLanguagePartial.cshtml 包含:

@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" 
          method="post" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> <select name="culture"
            onchange="this.form.submit();"
            asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
        </select>
    </form>
</div>

除此之外,我还创建了 2 个资源文件,ErrorMessages.ex-MX.resxErrorMessages.resx

在我的 HomeController 中我添加了这一行 ViewBag.Test = ErrorMessages.Test; 并且在索引视图中我添加了 <p>@ViewBag.Test</p>

当我查看该页面时,我看到带有语言的下拉菜单,但那里只列出了英语。我在页面上显示的文本来自 ErrorMessages.resx.

我是不是漏掉了一步?为什么西班牙人在任何地方都学不会?正如您将在下面看到的,我什至尝试将西班牙语设置为主要文化,但没有任何区别。

编辑:

我尝试从列表中删除英语,结果我得到的下拉列表仍然存在,这次它列出了西班牙语。但是,文本仍然是英文的。

然后我尝试将英语添加回项目中的第二个列表,并将英语设置为主要语言,但下拉列表仅显示 1 种语言,西班牙语现在消失了。

大约一周前我遇到了同样的问题。我用这个解决了它:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddMvc()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("es") };

        options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
}

不过,还有一个评论。在 ASP.NET Core 中,不应创建默认的文化资源,只能创建特定的:

所以,给定

Views/Shared/Layout.cshtml

仅创建

Resources/Views/Shared/Layout.es-MX.resx

另请注意,您通过此将西班牙语限制为墨西哥语,因此您应该有一个 es 后备,或者同时添加 eses-MX