介紹:
所有有關本地化的數據獲取,都是從統一的一個資源文件中獲取
1.創建虛擬類、資源文件,用於作為本地化數據的獲取源
2.Configure localization:支持view、data annotation、mvc
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
可以更改順序,甚至添加一個自定義區域性提供程序
var supportedCultures = new[]{"zh-CN","en-US"}; app.UseRequestLocalization(cultureOptions=> { cultureOptions.AddSupportedCultures(supportedCultures) .AddSupportedUICultures(supportedCultures) .SetDefaultCulture(supportedCultures[0]); cultureOptions.FallBackToParentCultures = true; });
4.注冊本地化服務,用於全局調用(單一實例)
services.AddSingleton<IStringLocalizer>((sp) => { var sharedLocalizer = sp.GetRequiredService<IStringLocalizer<SharedResource>>(); return sharedLocalizer; });
5.使用
view使用
@using Microsoft.AspNetCore.Mvc.Localization @inject Microsoft.Extensions.Localization.IStringLocalizer localizer <p>@Localizer["Use this area to provide additional information."]</p>
controller使用
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
@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
部分,使它將可供所有視圖使用:
<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
[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