我一直在按照此页面上的说明设置本地化:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization
但是,对我来说,它似乎不起作用。这是我所做的:
启动.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.resx
和 ErrorMessages.resx
。在我的 HomeController 中,我添加了这一行
ViewBag.Test = ErrorMessages.Test;
并在 Index View 中添加了 <p>@ViewBag.Test</p>
当我查看页面时,我会看到带有语言的下拉菜单,那里只列出了英语。我在页面上显示的文本来自
ErrorMessages.resx
。我错过了一步吗?为什么西类牙语在任何地方都没有被接受?正如您将在下面看到的,我什至尝试将西类牙语设置为主要文化,但没有区别。
编辑:
我尝试从列表中删除 eglish 并且我得到下拉列表的结果仍然存在,这次它列出了西类牙语。但是,文本仍然是英文。
然后我尝试将英语添加回项目中的第二个列表,并将英语设置为主要语言,下拉列表仅显示 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
回退,或者同时添加 es
和 es-MX
。关于c# - Asp.Net Core 中的本地化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46984323/