Как создать локализованный URL в ядре .net? - PullRequest
0 голосов
/ 17 мая 2019

Я реализовал локализацию в своем базовом приложении .net и использую файлы cookie для изменения культуры. Теперь я хочу, чтобы моя текущая культура была также в URL. Как мне этого добиться.

Чтобы изменить URL, я делаю следующее: -

      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        var locOptions = 
   app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();


        app.UseRequestLocalization(locOptions.Value);

        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        var culture = cultureInfo.Name;

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();
        app.UseSession();

        //configuring mvc routes...
        app.UseMvc(routes =>
        {
            routes.MapRoute(
               name: "areaRoute",
               template: "{area:exists}/{controller}/{action}/{id?}",
               defaults: new { controller = "Home", action = "Index" });

            routes.MapRoute(
                name: "default",
                template: "{culture}/{controller}/{action}/{id?}",
                defaults: new { culture = culture, controller = "Home", action = "Index" });
        });
    }

Я получаю текущую культуру из потока и передаю ее моему маршруту, но она всегда показывает стандартную культуру в URL. Культура в URL не меняется, когда я меняю культуру с помощью файлов cookie.

Любая помощь будет оценена.

Изменить: - My Configure Services выглядит следующим образом: -

'' '

public void ConfigureServices(IServiceCollection services)
       {
        //add authentication before all services
  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.AccessDeniedPath = "/Account/Forbidden";
                options.LoginPath = "/Account/Login";

            });

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromDays(30);//You can set Time   
        });

        //adding HttpContextAccessor middleware
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddRouting(options => options.LowercaseUrls = true);


        //configuration for multilanguage support
        services.AddLocalization();

        services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();

        //       services.AddMvc()
        //.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        //.AddDataAnnotationsLocalization();

        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("de"),
                new CultureInfo("en")
            };

            // CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;

            options.DefaultRequestCulture = new RequestCulture(culture: "de", uiCulture: "de");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            //options.RequestCultureProviders.Insert(0, new RouteValueRequestCultureProvider(supportedCultures));


            options.RequestCultureProviders = new List<IRequestCultureProvider>
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    };
        });



        //adding other services...
        ConfigureBusinessServices(services);
    }

У меня есть опция смены языка в приложении. И я делаю это так, на мой взгляд: -

@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();
    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="Language"
          asp-action="ChangeLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" 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>

Мой контроллер для изменения культуры: -

 [HttpPost]
        public IActionResult ChangeLanguage(string culture, string returnUrl)
        {

            ////_languageManager.ChangeCulture(model.culture, model.uiCulture);
            //_languageManager.ChangeCulture(culture, culture);

            Response.Cookies.Append(
    CookieRequestCultureProvider.DefaultCookieName,
    CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
    new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);


            return LocalRedirect(returnUrl);
        }

Проблема в том, что когда мое приложение запускается, оно показывает немецкую культуру по умолчанию также в URL. но когда я меняю язык на английский. Культура меняет все мои данные с показом английского языка, но в URL все равно отображается немецкий (де).

...