ASP.NET 核心 Web 应用程序中的语言没有改变
The Language does not change in the ASP.NET Core Web application
我按照 Globalization and localization and Building simple multilingual ASP.NET Core website 教程为我的应用程序添加语言切换。
所以,我创建了局部视图
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@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();
}
<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path"
method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture"
onchange="this.form.submit();"
asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"></select>
</form>
</div>
添加在 _Layout
的页脚
<div class="col-md-6 text-right">
@await Html.PartialAsync("_SelectLanguagePartial")
</div>
并像这样配置 Startup.cs:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("es"),
new CultureInfo("en")
};
options.DefaultRequestCulture = new RequestCulture(culture: "es", uiCulture: "es");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
我添加了一个 Resources
文件夹,其中
Views.Home.Index.es.resx
Views.Home.Index.en.resx
Views.Shared._Layout.es.resx
Views.Shared._Layout.en.resx
我也做了Install-Package Microsoft.AspNetCore.Authentication.Cookies
当我加载主页视图时,我有西班牙语选项 selected。但是当我尝试 select "English" 它加载时,但回滚了西班牙语版本,所以我最终无法看到我的英文内容。问题出在哪里?
您是否添加了 javascript 来使语言选择器回发?
(function () {
$("#selectLanguage select").change(function () {
$(this).parent().submit();
});
}());
您是否在 Configure 中连接了请求本地化中间件?
var locOptions= app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
你有没有在 HomeController 中添加这样的方法:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
为那些即使您已使用 Joe Auddette 的回答更新了代码但仍无法正常工作的人添加一个额外的回答。
CookieOptions
阻止了我很长时间才能使事情正常进行:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddYears(1),
IsEssential = true, //critical settings to apply new culture
Path = "/",
HttpOnly = false,
}
);
return LocalRedirect(returnUrl);
}
IsEssential
在源代码中有以下注释:
Indicates if this cookie is essential for the application to function
correctly. If true then consent policy checks may be bypassed. The
default value is false.
并且 consent policy
设置在 startup.cs
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies
// is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
我按照 Globalization and localization and Building simple multilingual ASP.NET Core website 教程为我的应用程序添加语言切换。
所以,我创建了局部视图
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@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();
}
<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path"
method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture"
onchange="this.form.submit();"
asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"></select>
</form>
</div>
添加在 _Layout
的页脚
<div class="col-md-6 text-right">
@await Html.PartialAsync("_SelectLanguagePartial")
</div>
并像这样配置 Startup.cs:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("es"),
new CultureInfo("en")
};
options.DefaultRequestCulture = new RequestCulture(culture: "es", uiCulture: "es");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
我添加了一个 Resources
文件夹,其中
Views.Home.Index.es.resx
Views.Home.Index.en.resx
Views.Shared._Layout.es.resx
Views.Shared._Layout.en.resx
我也做了Install-Package Microsoft.AspNetCore.Authentication.Cookies
当我加载主页视图时,我有西班牙语选项 selected。但是当我尝试 select "English" 它加载时,但回滚了西班牙语版本,所以我最终无法看到我的英文内容。问题出在哪里?
您是否添加了 javascript 来使语言选择器回发?
(function () {
$("#selectLanguage select").change(function () {
$(this).parent().submit();
});
}());
您是否在 Configure 中连接了请求本地化中间件?
var locOptions= app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
你有没有在 HomeController 中添加这样的方法:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
为那些即使您已使用 Joe Auddette 的回答更新了代码但仍无法正常工作的人添加一个额外的回答。
CookieOptions
阻止了我很长时间才能使事情正常进行:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddYears(1),
IsEssential = true, //critical settings to apply new culture
Path = "/",
HttpOnly = false,
}
);
return LocalRedirect(returnUrl);
}
IsEssential
在源代码中有以下注释:
Indicates if this cookie is essential for the application to function correctly. If true then consent policy checks may be bypassed. The default value is false.
并且 consent policy
设置在 startup.cs
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies
// is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});