Force all requests to use a single culture using U

2019-04-18 00:32发布

问题:

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

Some requests are still getting en-US

回答1:

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.

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