ASP.NET Core Request Localization Options

后端 未结 4 1323
失恋的感觉
失恋的感觉 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:54

    You can get Accept-Language header from the current Request and set default language. Your code should be something like this:

    services.Configure(options =>
    {
        //...
    
        options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
        {                    
           //...
           var userLangs = context.Request.Headers["Accept-Language"].ToString();
           var firstLang = userLangs.Split(',').FirstOrDefault();
           var defaultLang = string.IsNullOrEmpty(firstLang) ? "en" : firstLang;
           return Task.FromResult(new ProviderCultureResult(defaultLang, defaultLang));
       }));
    });
    

提交回复
热议问题