- A+
所属分类:.NET技术
.NET Core WebApi 多语言本地化,动态切换多语言
-
原生的.net core webapi 动态多语言本地话
-
具体更多详细内容,可以参考官方文档
-
首先看效果图
-
整体项目结构图
-
开始前需要讲一些重要的点
-
1.是通过文件命名空间的路径去找寻的,比如 Resource.cs 是在和多语言Resource.xxxx.resx文件同一级别的 2.参考下图,不然多语言翻译时是找寻不到的
-
-
-
ConfigureServices里面进行以下配置
services.AddLocalization(); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new List<CultureInfo> { new CultureInfo("en-US"),//英文 new CultureInfo("zh-Hans"),//简体中文 new CultureInfo("zh-Hant")//繁体中文-台湾 }; options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; options.RequestCultureProviders = new List<IRequestCultureProvider> { new CultureRequestCultureProvider() }; });
-
Configure下加入如下代码
//多语言配置 var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>(); app.UseRequestLocalization(localizeOptions.Value);
-
其中关键的 CultureRequestCultureProvider.cs 代码内容如下 (通过HttpContext 的Headers 传参 Accept-Language来实现动态切换语言的)
public class CultureRequestCultureProvider : RequestCultureProvider { public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException(); } #region 方式一从Cookies里面按需获取语言 注释 //var CULTURE_String = "CULTURE"; //var CultureValue = httpContext.Request.Cookies[CULTURE_String]?.ToString() ?? ""; //if (string.IsNullOrWhiteSpace(CultureValue)) //{ // CultureValue = "zh-Hans"; // httpContext.Response.Cookies.Append(key: CULTURE_String, value: CultureValue, options: new CookieOptions() { Expires = DateTime.Now.AddYears(1) }); //} #endregion //方式二 从Headers里面按需获取语言 var culture = new StringSegment("zh-Hans"); var uiCulture = new StringSegment("zh-Hans"); var lang = httpContext.Request.Headers["Accept-Language"].ToString() ?? ""; switch (lang) { case "en-US": //英文 culture = new StringSegment("en-US"); uiCulture = new StringSegment("en-US"); break; case "zh-Hans": //简体中文 culture = new StringSegment("zh-Hans"); uiCulture = new StringSegment("zh-Hans"); break; case "zh-Hant": //繁体中文-台湾 culture = new StringSegment("zh-Hant"); uiCulture = new StringSegment("zh-Hant"); break; default: goto case "zh-Hans"; } return Task.FromResult(new ProviderCultureResult(culture, uiCulture)); } }
-
Resource.cs 以及多语言文件的代码如下
namespace DynamicMultilanguage.Localize { public class Resource { } }
-
在控制器里面使用时
private readonly IStringLocalizer<Resource> _localizer; public HomeController(IStringLocalizer<Resource> localizer) { _localizer = localizer; } [HttpGet] public object Get() { var culturesValue = _localizer["Home"]; var culturesValueParams = _localizer["HomeTitie", "雨太阳", "66666"]; return new { culturesValue, culturesValueParams }; }
按照以上操作,一个简答的WebApi的多语言切换已经完成了