Asp.Net Core中的本地化 [英] Localization in Asp.Net Core
问题描述
我一直按照本页上的说明设置本地化:
I have been following the instructions on this page to setup Localization:
https://docs.microsoft.com/zh-CN /aspnet/core/fundamentals/localization
但是,对我而言,它似乎不起作用.这是我所做的:
However, for me it just doesn't seem to work. Here is what I have done:
Startup.cs:
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包含以下内容:
My Layout.cshtml contains the following:
@await Html.PartialAsync("_SelectLanguagePartial")
和我的_SelectLanguagePartial.cshtml包含:
and my _SelectLanguagePartial.cshtml contains:
@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>
除此之外,我还创建了两个资源文件ErrorMessages.ex-MX.resx
和ErrorMessages.resx
.
In addition to this, I have created 2 resource files, ErrorMessages.ex-MX.resx
and ErrorMessages.resx
.
在我的HomeController中,我添加了这行ViewBag.Test = ErrorMessages.Test;
,在索引视图中,我添加了<p>@ViewBag.Test</p>
In my HomeController I have added this line ViewBag.Test = ErrorMessages.Test;
and in the Index view I added <p>@ViewBag.Test</p>
当我查看页面时,会看到带有语言的下拉列表,并且只列出了英语.我在页面上显示的文本是来自ErrorMessages.resx
的文本.
When I look at the page I see the drop down with languages and it only has English listed there. The text that I displayed on the page is the one coming from ErrorMessages.resx
.
我错过了一步吗?为什么西班牙语在任何地方都没有被拾起?正如您将在下面看到的那样,我什至尝试将西班牙语设置为主要文化,但没有区别.
Am I missing a step? How come Spanish is not getting picked up anywhere? As you will see below, I even tried setting spanish as the main culture, yet no difference.
我尝试从列表中删除eglish,结果下拉菜单仍然存在,这次列出了西班牙语.但是,该文本仍为英文.
I tried removing eglish from the list and the result that I got the dropdown was still there and this time it had Spanish listed. However, the text was still in English.
然后,我尝试将英语作为第二项添加回该列表中,并将英语设置为主语言,并且下拉菜单仅显示一种语言,而西班牙语消失了.
Then I tried adding English back as a second list in the item and setting english as the main language and the dropdown only displayed 1 language and spanish was now gone.
推荐答案
大约一周前,我遇到了同样的问题.我用这个解决了:
I had this same problem around a week ago. I solved it with this:
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中,不应创建默认的区域性资源,而只能创建特定的区域性资源:
One more comment, though. In ASP.NET Core, the default culture resource should not be created, only specific ones:
所以,给定
Views/Shared/Layout.cshtml
仅创建
Resources/Views/Shared/Layout.es-MX.resx
还要注意,您以此限制西班牙语为墨西哥语,因此您应该使用es
后备广告,或同时添加es
和es-MX
.
Do notice, also, that you are limiting Spanish to Mexican by this, so you should either have a es
fallback, or add both es
and es-MX
.
这篇关于Asp.Net Core中的本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!