//自定义时区请求处理对象 public class RouteDataRequestCultureProvider : RequestCultureProvider { public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) { //在这里切换系统语言 //以下是通过Headers传值来切换语言,你也可以通过路由、cookie、url传值来切换 if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var listCulture = new List<string> { "zh-CN", "en-US" }; string culture = "zh-CN"; if (httpContext.Request.Headers.ContainsKey("Content-Language")) { culture = httpContext.Request.Headers["Content-Language"]; if (culture.Contains("-")) { var cultureArr = culture.Split('-'); if (cultureArr?.Length == 2) { culture = $"{cultureArr[0].ToLower()}-{cultureArr[1].ToUpper()}"; } } else { culture = culture.ToLower(); } } string uiCulture = culture = listCulture.Contains(culture) ? culture : "zh-CN"; var providerResultCulture = new ProviderCultureResult(culture, uiCulture); return Task.FromResult(providerResultCulture); } }
//配置服务 services.Configure<RequestLocalizationOptions>(opt => { var supportedCultures = new[] { new CultureInfo(DefaultLanguage), new CultureInfo("en-US") }; opt.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(DefaultLanguage); opt.SupportedCultures = supportedCultures; opt.SupportedUICultures = supportedCultures; opt.RequestCultureProviders = new List<IRequestCultureProvider> { new RouteDataRequestCultureProvider() }; })
//启用请求本地化中间件 app.UseRequestLocalization();