博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DotNETCore 学习笔记 全球化和本地化
阅读量:6879 次
发布时间:2019-06-26

本文共 7734 字,大约阅读时间需要 25 分钟。

Globalization and localization****************************************************************************************************using Microsoft.AspNet.Localization;using Microsoft.AspNet.Mvc.Localization;namespace Localization.StarterWeb.Controllers{    public class BookController : Controller    {        //private readonly IStringLocalizer
_localizer; private readonly IHtmlLocalizer
_localizer; public BookController(IHtmlLocalizer
localizer) { _localizer = localizer; } public IActionResult Hello(string name) { ViewData["Message"] = _localizer["
Hello
{0}", name]; return View(); }public class TestController : Controller { private readonly IStringLocalizer _localizer; private readonly IStringLocalizer _localizer2; public TestController(IStringLocalizerFactory factory) { _localizer = factory.Create(typeof(SharedResource)); _localizer2 = factory.Create("SharedResource", location: null); } public IActionResult About() { ViewData["Message"] = _localizer["Your application description page."] + " loc 2: " + _localizer2["Your application description page."]; return View(); } public class SharedResource { } public class InfoController : Controller { private readonly IStringLocalizer
_localizer; private readonly IStringLocalizer
_sharedLocalizer; public InfoController(IStringLocalizer
localizer, IStringLocalizer
sharedLocalizer) { _localizer = localizer; _sharedLocalizer = sharedLocalizer; } public string TestLoc() { string msg = "Shared resx: " + _sharedLocalizer["Hello!"] + " Info resx " + _localizer["Hello!"]; return msg; }****************************************************************************************************View localization@using Microsoft.AspNet.Mvc.Localization@inject IViewLocalizer Localizer@{ ViewData["Title"] = Localizer["About"];}

@ViewData["Title"].

@ViewData["Message"]

@Localizer["Use this area to provide additional information."]

----------------------------------------------------------------------------------@Localizer["
Hello
{0}!", UserManager.GetUserName(User)]----------------------------------------------------------------------------------------@using Microsoft.AspNet.Mvc.Localization@using Localization.StarterWeb.Services@inject IViewLocalizer Localizer@inject IHtmlLocalizer
SharedLocalizer@{ ViewData["Title"] = Localizer["About"];}

@ViewData["Title"].

@SharedLocalizer["Hello!"]

----------------------------------------------------------------------------------------DataAnnotations localizationDataAnnotations error messages are localized with IStringLocalizer
. Using the option ResourcesPath = "Resources", the error messages in RegisterViewModel can be stored in either of the following paths:•Resources/ViewModels.Account.RegisterViewModel.fr.resx•Resources/ViewModels/Account/RegisterViewModel.fr.resx+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public class RegisterViewModel { [Required(ErrorMessage = "The Email field is required.")] [EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")] [Display(Name = "Email")] public string Email { get; set; } [Required(ErrorMessage = "The Password field is required.")] [StringLength(8, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } }The runtime doesn’t look up localized strings for non-validation attributes. In the code above, “Email” (from [Display(Name = "Email")]) will not be localized.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Configuring localizationpublic void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddMvc() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization();-------------------------------------------------------------------------------------Localization middleware public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("en-AU"), new CultureInfo("en-GB"), new CultureInfo("en"), new CultureInfo("es-ES"), new CultureInfo("es-MX"), new CultureInfo("es"), new CultureInfo("fr-FR"), new CultureInfo("fr"), }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures });1.QueryStringRequestCultureProvider2.CookieRequestCultureProvider3.AcceptLanguageHeaderRequestCultureProvider--------------------------------------------------------------------------------------------Using a custom provider:services.Configure
(options =>{ var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("fr") }; options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context => { // My custom request culture logic return new ProviderCultureResult("en"); }));});--------------------------------------------------------------------------------------------Resource file naming:Resource name Dot or path namingResources/Controllers.HomeController.fr.resx Dot Resources/Controllers/HomeController.fr.resx Path Setting the culture programmaticallyThe Views/Shared/_SelectLanguagePartial.cshtml file allows you to select the culture from the list of supported cultures:@using Microsoft.AspNet.Builder@using Microsoft.AspNet.Http.Features@using Microsoft.AspNet.Localization@using Microsoft.AspNet.Mvc.Localization@using Microsoft.Extensions.Options@inject IViewLocalizer Localizer@inject IOptions
LocOptions@{ var requestCulture = Context.Features.Get
(); var cultureItems = LocOptions.Value.SupportedUICultures .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName }) .ToList();}
@Localizer["Language:"]
@RenderBody()

© 2015 - Localization.StarterWeb

@await Html.PartialAsync("_SelectLanguagePartial")
[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); }Terms:•Globalization (G11N): The process of making an app support different languages and regions.•Localization (L10N): The process of customizing an app for a given language and region.•Internationalization (I18N): Describes both globalization and localization.•Culture: It is a language and, optionally, a region.•Neutral culture: A culture that has a specified language, but not a region. (for example “en”, “es”)•Specific culture: A culture that has a specified language and region. (for example “en-US”, “en-GB”, “es-CL”)•Locale: A locale is the same as a culture.

 

转载于:https://www.cnblogs.com/ziranquliu/p/5871299.html

你可能感兴趣的文章
windows下两个无线网卡 一个内网 一个外网
查看>>
tcp nat 负载均衡
查看>>
起点,游戏开发的梦想与技能点
查看>>
MPLS 流量工程的配置与各大属性调整详解
查看>>
107个常用Javascript语句
查看>>
我的友情链接
查看>>
Dataram_RAMDisk_v4_0_0安装和配置
查看>>
在window XP下使用vsphere client 5.5 访问vCenter 或者 ESXi5.5 连接错误
查看>>
35 个超棒的 Coming Soon 页面设计案例
查看>>
C语言第四天(位运算)
查看>>
硬RAID可以为NVMe SSD数据可靠性保驾护航吗?
查看>>
iPad 2 移植Siri 新手完全教程 适用所有越狱设备
查看>>
编程题:用函数实现,用户输入年月日,来计算出该日期为当年第几天?
查看>>
Pro Android学习笔记(十一):了解Intent(中)
查看>>
小程序混合框架HERA1.1.0发布
查看>>
linux下svn+rsync+inotify实现代码自动同步
查看>>
MYSQL主从+amoeba读写分离(一)
查看>>
tomcat并发量和内存的关系
查看>>
J2EE操作系统调优
查看>>
linux服务器校验时间
查看>>