在ASP.Net Core 2.2中更改语言后,URL中的区域性名称不会更改

时间:2019-02-14 14:44:37

标签: asp.net-core model-view-controller localization asp.net-core-2.1

我按照https://joonasw.net/view/aspnet-core-localization-deep-dive教程为应用程序添加了语言切换。

我的问题是,在使用选择框切换到另一种语言后,区域性名称在浏览器URL中没有更改。

逐步:

  • 我运行该应用程序,它以默认的匈牙利语(hu-HU)打开
  • 我将选择框的语言更改为英语,并将页面内容更改为英语,但是在浏览器URL中,我再次看到/ hu-HU /。不会更改为“ / en-US /”。

我清除的代码:

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        #region Cookies
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        #endregion

        #region Localization
        services.AddLocalization(options => options.ResourcesPath = "");
        services.TryAddSingleton<IStringLocalizer, ZLocalizer>();
        services.Configure<RequestLocalizationOptions>(
        options =>
        {
            var supportedCultures = new List<CultureInfo>
            {
               new CultureInfo("en-US"),
               new CultureInfo("hu-HU"),
            };
            options.DefaultRequestCulture = new RequestCulture(culture: "hu-HU", uiCulture: "hu-HU");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            services.AddSingleton(options);
        });
        #endregion

        services.AddMvc()
        #region Localization
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization(o =>
            {
                o.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return factory.Create(typeof(SharedResources));
                };
            })
        #endregion
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env )
    {
        app.UseCookiePolicy();

        #region Multilanguage
        var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(localizationOptions.Value);
        #endregion

        // Multilanguage and culture injection around UseMvc
        app.UseRouter(routes =>
        {
            routes.MapMiddlewareRoute("{culture=hu-HU}/{*mvcRoute}", subApp =>
            {
                #region Multilanguage
                subApp.UseRequestLocalization(localizationOptions.Value);
                #endregion

                subApp.UseMvc(mvcRoutes =>
                {
                    mvcRoutes.MapRoute(
                        name: "hidehome",
                        template: "{culture=hu-HU}/{action=Index}/{id?}",
                        defaults: new { controller = "Home" }
                        );

                    mvcRoutes.MapRoute(
                        name: "default",
                        template: "{culture=hu-HU}/{controller=Home}/{action=Index}/{id?}");
                });
            });
        });
    }
}

局部视图

@using System.Globalization;
@using Microsoft.AspNetCore.Builder;
@using Microsoft.Extensions.Options;
@using Microsoft.AspNetCore.Localization;

@inject IOptions<RequestLocalizationOptions> LocOps

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOps.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
}

<div title="@Lang["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">
        @Lang["Language:"] <select name="culture"
                                        onchange="this.form.submit();"
                                        asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"></select>
    </form>
</div>

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),
                    //IsEssential = true,  //critical settings to apply new culture 
                    //Path = "/",
                    //HttpOnly = false,
                }
            );

            return LocalRedirect(returnUrl);
        }



问题出在哪里?谢谢您的帮助!

0 个答案:

没有答案