使用UseRequestLocalization强制所有请求使用单一区域性 [英] Force all requests to use a single culture using UseRequestLocalization

查看:664
本文介绍了使用UseRequestLocalization强制所有请求使用单一区域性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ASP.NET Core RC 2中设置固定区域性? 我的Startup.cs:

How can I set a fixed culture in ASP.NET Core RC 2? My 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

推荐答案

请求本地化意味着,对于每个请求,框架都将尝试使用请求者首选的本地化.无论用户在其客户端浏览器中进行了什么设置,您都希望将应用程序的默认区域性更改为始终使用您的语言环境.为此,您可以使用小型中间件.

Request Localization means that, for each request, the framework will try to use the localization preferred by the requester. What you want is to change the default culture of your application to always use your locale, no matter what the user has set in her client browser. For this you may use a small middleware.

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

In your Startup.cs file add the following at the very top:

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

}

并在项目中的某个位置添加中间件:

And add your middleware, somewhere in your project:

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

这篇关于使用UseRequestLocalization强制所有请求使用单一区域性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆