.Net Core 本地化&全球化 实践
介绍:
所有有关本地化的数据获取,都是从统一的一个资源文件中获取
1.创建虚拟类、资源文件,用于作为本地化数据的获取源
2.Configure localization:支持view、data annotation、mvc
1 2 3 4 5 6 7 8 | services.AddLocalization(options => options.ResourcesPath = "Resources" ); services.AddMvc() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create( typeof (SharedResource)); }).AddMvcLocalization() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); |
3.Localization middleware:
默认排序为
QueryStringRequestCultureProvider
CookieRequestCultureProvider
AcceptLanguageHeaderRequestCultureProvider
可以更改顺序,甚至添加一个自定义区域性提供程序
1 2 3 4 5 6 7 8 9 | var supportedCultures = new []{ "zh-CN" , "en-US" }; app.UseRequestLocalization(cultureOptions=> { cultureOptions.AddSupportedCultures(supportedCultures) .AddSupportedUICultures(supportedCultures) .SetDefaultCulture(supportedCultures[0]); cultureOptions.FallBackToParentCultures = true ; }); |
4.注册本地化服务,用于全局调用(单一实例)
1 2 3 4 5 | services.AddSingleton<IStringLocalizer>((sp) => { var sharedLocalizer = sp.GetRequiredService<IStringLocalizer<SharedResource>>(); return sharedLocalizer; }); |
5.使用
view使用
1 2 3 4 | @using Microsoft.AspNetCore.Mvc.Localization @inject Microsoft.Extensions.Localization.IStringLocalizer localizer < p >@Localizer["Use this area to provide additional information."]</ p > |
controller使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class BookController : Controller { private readonly IStringLocalizer _localizer; public BookController(IStringLocalizer localizer) { _localizer = localizer; } public IActionResult Hello( string name) { ViewData[ "Message" ] = _localizer[ "<b>Hello</b><i> {0}</i>" , name]; return View(); } |
DataAnnotations 错误消息自动添加,
因为Configure localization步骤中,已经添加了支持AddDataAnnotationsLocalization
6.视图,默认语言可自配置
以编程方式设置区域性
共享视图:Views/Shared/_SelectLanguagePartial.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | @using Microsoft.AspNetCore.Builder @using Microsoft.AspNetCore.Http.Features @using Microsoft.AspNetCore.Localization @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Options @inject IViewLocalizer Localizer @inject IOptions< RequestLocalizationOptions > LocOptions @{ var requestCulture = Context.Features.Get< IRequestCultureFeature >(); var cultureItems = LocOptions.Value.SupportedUICultures .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName }) .ToList(); var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}"; } < div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name"> < form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" method="post" class="form-horizontal" role="form"> < label asp-for="@requestCulture.RequestCulture.UICulture.Name"> @Localizer["Language:"] </ label > < select name="culture" onchange="this.form.submit();" asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"> </ select > </ form > </ div > |
Views/Shared/_SelectLanguagePartial.cshtml 文件添加到了布局文件的 footer
部分,使它将可供所有视图使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | < div class="container body-content" style="margin-top:60px"> @RenderBody() < hr > < footer > < div class="row"> < div class="col-md-6"> < p >© @System.DateTime.Now.Year - Localization</ p > </ div > < div class="col-md-6 text-right"> @await Html.PartialAsync("_SelectLanguagePartial") </ div > </ div > </ footer > </ div > |
将Language的设置保存至cookie
1 2 3 4 5 6 7 8 9 10 11 | [HttpPost] public IActionResult SetLanguage( string culture, string returnUrl) { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue( new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } ); return LocalRedirect(returnUrl); } |
7.优化
- 自定义TagHelper
- string extention
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库