How to set culture for date binding in Asp.Net Core?

江枫思渺然 提交于 2019-11-29 09:29:19

A couple of things. I'm not sure you can push a new settings object into the middleware like that (You probably can), but most of the time I have seen it used in the ConfigureServices method like so :

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-NZ");
        options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US"), new CultureInfo("en-NZ") };
    });

    services.AddMvc();
}

Second. The order of your middleware is very important. Ensure that your call to UseRequestLocalization happens before UseMvc. Infact it should probably be the first thing in your pipeline unless there is a specific reason it can't be.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseRequestLocalization();
    app.UseMvc();
}

And finally, can you try removing all the providers from the pipeline (One of which is a cookie provider. I can't fathom why you would have this cookie but let's just try).

In your configure method call clear on the RequestCultureProviders list. This should ensure that there is nothing else there to set a culture.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB");
        options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") };
        options.RequestCultureProviders.Clear();
    });

    services.AddMvc();
}

More info : http://dotnetcoretutorials.com/2017/06/22/request-culture-asp-net-core/

Updated answer for aspnet core 2.0

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var supportedCultures = new[] { new CultureInfo("es-CO") };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("es-CO"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

        // other configurations after (not before)
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!