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

时间:2016-06-14 14:57:45

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

如何在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

1 个答案:

答案 0 :(得分:0)

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

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<MyRequestLocalizationMiddleware>();
    ...

}

在项目的某个地方添加中间件:

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);
        }
    }
}