如何在ASP.NET Core 3.1中创建本地化路由和语言选择器?

如何在ASP.NET Core 3.1中创建本地化路由和语言选择器?,asp.net,asp.net-core,asp.net-core-3.0,Asp.net,Asp.net Core,Asp.net Core 3.0,作为一名新手,我想做三件事: 创建本地化路由,如: www.mywebsite.com/fr/controller/action/在URL中隐藏区域性如果 默认文化(英文)www.mywebsite.com/controller/action/ 将用户区域性首选项保存在cookie中,以便在下次访问时自动使用 创建语言选择器 我可以让这3点分开工作,但我不能把它们全部用在一起。我真的不知道如何继续。(使用控制器或过滤器…) 对于我在下面所做的路由,除了默认语言仍然出现在url中之外,它似乎正在工

作为一名新手,我想做三件事:

  • 创建本地化路由,如: www.mywebsite.com/fr/controller/action/在URL中隐藏区域性如果 默认文化(英文)www.mywebsite.com/controller/action/

  • 将用户区域性首选项保存在cookie中,以便在下次访问时自动使用

  • 创建语言选择器

  • 我可以让这3点分开工作,但我不能把它们全部用在一起。我真的不知道如何继续。(使用控制器或过滤器…)

    对于我在下面所做的路由,除了默认语言仍然出现在url中之外,它似乎正在工作。对我来说似乎不是很干净,很确定有更好的方法来实现这一点

        public class CultureFilter : IRequestCultureProvider
    {
        private readonly CultureInfo defaultCulture;
        private readonly CultureInfo defaultUICulture;
    
        public CultureFilter(RequestCulture requestCulture)
        {
            this.defaultCulture = requestCulture.Culture;
            this.defaultUICulture = requestCulture.UICulture;
        }
    
        public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
        {
            //Parsing language from url path, which looks like "/en/home/index"
            PathString url = httpContext.Request.Path;
    
            // Test any culture in route
            if (url.ToString().Length <= 1)
            {
                // Set default Culture and default UICulture
                return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
            }
    
            var parts = httpContext.Request.Path.Value.Split('/');
            var culture = parts[1];
    
            // Test if the culture is properly formatted
            if (!Regex.IsMatch(culture, @"^[a-z]{2}(-[A-Z]{2})*$"))
            {
                // Set default Culture and default UICulture
                return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
            }
    
            // Set Culture and UICulture from route culture parameter
            return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(culture, culture));
        }
    }
    
    Startup.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting(options => options.LowercaseUrls = true);
            services.AddLocalization(options => options.ResourcesPath = "Resources");
    
            services
                .AddControllersWithViews()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();
    
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var cultures = new[]
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr"),
                    new CultureInfo("es")
                };
    
                options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
                options.SupportedCultures = cultures;
                options.SupportedUICultures = cultures;
    
                options.RequestCultureProviders.Insert(0, new CultureFilter(options.DefaultRequestCulture));
            });
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRequestLocalization();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Static/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "localization",
                    pattern: "{culture=en}/{controller=Static}/{action=Index}/{id?}");
    
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Static}/{action=Index}/{id?}");
            });
        }
    }
    
    公共类启动
    {
    公共启动(IConfiguration配置)
    {
    配置=配置;
    }
    公共IConfiguration配置{get;}
    //此方法由运行时调用。请使用此方法将服务添加到容器中。
    public void配置服务(IServiceCollection服务)
    {
    services.AddRouting(options=>options.LowercaseUrls=true);
    services.AddLocalization(options=>options.ResourcesPath=“Resources”);
    服务
    .AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.后缀)
    .AddDataAnnotationsLocalization();
    配置(选项=>
    {
    var cultures=new[]
    {
    新文化信息(“en”),
    新文化资讯(“fr”),
    新文化信息(“es”)
    };
    options.DefaultRequestCulture=新的RequestCulture(区域性:“en”,uiCulture:“en”);
    options.SupportedCultures=文化;
    options.supporteducultures=文化;
    Insert(0,新的CultureFilter(options.DefaultRequestCulture));
    });
    }
    //此方法由运行时调用。请使用此方法配置HTTP请求管道。
    public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
    {
    app.UseRequestLocalization();
    if(env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    其他的
    {
    app.UseExceptionHandler(“/Static/Error”);
    //默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(端点=>
    {
    endpoints.MapControllerRoute(
    名称:“本地化”,
    模式:“{culture=en}/{controller=Static}/{action=Index}/{id?}”);
    endpoints.MapControllerRoute(
    名称:“默认”,
    模式:“{controller=Static}/{action=Index}/{id?}”);
    });
    }
    }
    

    感谢您的帮助。

    在ASP.NET Core中有一个可用于处理本地化的扩展:
    Microsoft.Extensions.localization
    :在ASP.NET Core中有一个可用于处理本地化的扩展:
    Microsoft.Extensions.localization
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting(options => options.LowercaseUrls = true);
            services.AddLocalization(options => options.ResourcesPath = "Resources");
    
            services
                .AddControllersWithViews()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();
    
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var cultures = new[]
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr"),
                    new CultureInfo("es")
                };
    
                options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
                options.SupportedCultures = cultures;
                options.SupportedUICultures = cultures;
    
                options.RequestCultureProviders.Insert(0, new CultureFilter(options.DefaultRequestCulture));
            });
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRequestLocalization();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Static/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "localization",
                    pattern: "{culture=en}/{controller=Static}/{action=Index}/{id?}");
    
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Static}/{action=Index}/{id?}");
            });
        }
    }