使用UseRequestLocalization强制所有请求使用单个区域性

如何在ASP.NET Core RC 2中设置固定文化? 我的Startup.cs

 var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("pt-BR", "pt-BR"), SupportedCultures = new[] { new CultureInfo("pt-BR") }, SupportedUICultures = new[] { new CultureInfo("pt-BR") } }; options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context => await Task.FromResult(new ProviderCultureResult("pt-BR", "pt-BR")))); app.UseRequestLocalization(options); 

一些请求仍然是en-US

请求本地化意味着,对于每个请求,框架将尝试使用请求者首选的本地化。 您想要的是将应用程序的默认文化更改为始终使用您的区域设置,无论用户在其客户端浏览器中设置了什么。 为此,您可以使用一个小型中间件。

Startup.cs文件中,在最顶部添加以下内容:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-BR"); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-BR"); app.UseMiddleware(); ... } 

并在项目的某处添加中间件:

 using Microsoft.AspNetCore.Http; using System.Globalization; using System.Threading.Tasks; namespace MyNamespace { public class MyRequestLocalizationMiddleware { private readonly RequestDelegate _next; public MyRequestLocalizationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var defaultCulture = new CultureInfo("pt-BR"); SetCurrentCulture(defaultCulture, defaultCulture); await _next(context); } private void SetCurrentCulture(CultureInfo culture, CultureInfo uiCulture) { CultureInfo.CurrentCulture = new CultureInfo(culture.Name); } } }