在下拉菜单中切换区域性会重定向到默认区域性

时间:2019-03-29 11:31:57

标签: c# asp.net asp.net-mvc core

我想提供在本地化中使用的设置和其他相关详细信息,以使多语言选项可以正常工作。当我将文化查询字符串添加到URL时,内容语言会正确更改,但每次在文化(语言)之间进行切换时,都会像我希望的那样使用下拉菜单使之成为默认文化。

我遵循在启动,相关控制器和视图中设置本地化的规则。

  1. 启动(名称空间和配置构造器没有问题)

    public IConfiguration Configuration { get; }
    
    public void ConfigureServices(IServiceCollection services)
    {
        //Add Localization
        services.AddLocalization(opts =>
        {
            opts.ResourcesPath = "Resources";
        });
    
        services.AddDbContext<OfferDbContext>(x =>
        {
            x.UseSqlServer(Configuration["Database:OfferDb"]);
        });
                                  .AddEntityFrameworkStores<OfferDbContext>()
                                    .AddDefaultTokenProviders();
    
        services.AddMvc().
            AddViewLocalization(opts =>
            {
                opts.ResourcesPath = "Resources";
            }).AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix).
             AddDataAnnotationsLocalization().
            SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddAntiforgery(a => a.HeaderName = "XSRF-TOKEN");
    
        services.Configure<RequestLocalizationOptions>(opts =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("az-Latn-AZ"),
                new CultureInfo("en-US"),
                new CultureInfo("en-GB"),
                new CultureInfo("ru-RU")
            };
    
            opts.DefaultRequestCulture = new RequestCulture("en-US");
            opts.SupportedCultures = supportedCultures;
            opts.SupportedUICultures = supportedCultures;
           // services.AddSingleton(opts);
        });
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //Request Localization
        var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);
        app.UseAuthentication();
        app.UseCookiePolicy();
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                    name: "root",
                    template: "{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });
    
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    } }

  2. 控制器/操作

 private readonly OfferDbContext _offerDbContext;
        private readonly IStringLocalizer<HomeController> _localizer;

            public HomeController(OfferDbContext offerDbContext, IStringLocalizer<HomeController> localizer)
        {
            _offerDbContext = offerDbContext;
            _localizer = localizer;
        }



[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. PartialView
@using System.Threading.Tasks
@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();
}

<form asp-controller="Home" asp-action="SetLanguage"
      asp-route-returnUrl="@Context.Request.Path"
      method="post" class="form-horizontal">
    @Localizer["Language:"] <select name="culture" onchange="this.form.submit();"
                                    asp-for="@requestCulture.RequestCulture.UICulture.Name"
                                    asp-items="cultureItems"></select>
</form>

4.View(索引)的一部分

@using System.Threading
@using Microsoft.AspNetCore.Mvc.Localization
@model Foroffer.Models.ViewModels.SlideViewModel

@inject IViewLocalizer Localizer

<button class="infotool" id="mynews">
                        <p>@Localizer["Foroffer"]</p>
                    </button>


我还有一些资源文件,这些文件可以翻译给定的Localizer(Foroffer)。文件夹结构如下:https://prnt.sc/n4cuko

请仔细检查,如果需要任何其他信息,我随时可以与您分享。

0 个答案:

没有答案