ASP.NET Core Request Localization Options

后端 未结 4 1325
失恋的感觉
失恋的感觉 2021-02-05 08:17

Here is my custom request culture provider which returns \"en\" as a default culture if no culture specified in url (for example http://sypalo.com/ru or http://sypalo.com/en). M

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-05 08:58

    Inside your public class Startup:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //...
    
        app.Use((context, next) =>
        {
            //get client prefered language
            var userLangs = context.Request.Headers["Accept-Language"].ToString();
            var firstLang = userLangs.Split(',').FirstOrDefault();
    
            //set allowed alanguage
            var lang = "en"; //default
            switch (firstLang)
            {
                case "hy": //allowed
                case "ru": //allowed
                    lang = firstLang; 
                    break;
                default:
                    //client language not supported
                    lang = "en"; //use our default
                    break;
            }
    
            //switch culture
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    
            //save for later use
            context.Items["ClientLang"] = lang;
            context.Items["ClientCulture"] = Thread.CurrentThread.CurrentUICulture.Name;
            
            // Call the next delegate/middleware in the pipeline
            return next();
        });
    
        //... then goes app.UseMvc etc..
    
    }
    

提交回复
热议问题