ASP.NET Core Web应用程序中的语言不会更改

时间:2017-07-24 14:13:20

标签: asp.net-core asp.net-core-1.1 asp.net-core-localization

我按照Globalization and localizationBuilding 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

当我加载主视图时,我选择了西班牙语选项。但是当我尝试选择“英语”时,它会加载,但回滚西班牙语版本,所以我终于看不到我的英文内容了。问题在哪里?

2 个答案:

答案 0 :(得分:4)

您是否添加了javascript以使语言选择器回发?

(function () {
$("#selectLanguage select").change(function () {
    $(this).parent().submit();
});
}());

您是否在配置中连接了请求本地化中间件?

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);
}

答案 1 :(得分:3)

即使您已经用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在源代码中有以下注释:

  

指示此cookie对于应用程序正常运行是否必不可少   正确地。如果为true,则可以绕过同意策略检查。的   默认值为false。

并且consent policystartup.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;
});