Globalization and localization
****************************************************************************************************
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc.Localization; namespace Localization.StarterWeb.Controllers
{
public class BookController : Controller
{
//private readonly IStringLocalizer<AboutController> _localizer;
private readonly IHtmlLocalizer<BookController> _localizer; public BookController(IHtmlLocalizer<BookController> localizer)
{
_localizer = localizer;
} public IActionResult Hello(string name)
{
ViewData["Message"] = _localizer["<b>Hello</b><i> {0}</i>", 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<InfoController> _localizer;
private readonly IStringLocalizer<SharedResource> _sharedLocalizer; public InfoController(IStringLocalizer<InfoController> localizer,
IStringLocalizer<SharedResource> 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"];
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3> <p>@Localizer["Use this area to provide additional information."]</p> ----------------------------------------------------------------------------------
@Localizer["<i>Hello</i> <b>{0}!</b>", UserManager.GetUserName(User)]
----------------------------------------------------------------------------------------
@using Microsoft.AspNet.Mvc.Localization
@using Localization.StarterWeb.Services @inject IViewLocalizer Localizer
@inject IHtmlLocalizer<SharedResource> SharedLocalizer @{
ViewData["Title"] = Localizer["About"];
}
<h2>@ViewData["Title"].</h2> <h1>@SharedLocalizer["Hello!"]</h1> ---------------------------------------------------------------------------------------- DataAnnotations localization DataAnnotations error messages are localized with IStringLocalizer<T>. 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(, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = )]
[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 localization public 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
}); .QueryStringRequestCultureProvider
.CookieRequestCultureProvider
.AcceptLanguageHeaderRequestCultureProvider
--------------------------------------------------------------------------------------------
Using a custom provider:
services.Configure<RequestLocalizationOptions>(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(, new CustomRequestCultureProvider(async context =>
{
// My custom request culture logic
return new ProviderCultureResult("en");
}));
}); --------------------------------------------------------------------------------------------
Resource file naming: Resource name Dot or path naming
Resources/Controllers.HomeController.fr.resx Dot
Resources/Controllers/HomeController.fr.resx Path Setting the culture programmatically
The 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<RequestLocalizationOptions> LocOptions @{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
} <div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path"
method="post" class="form-horizontal" role="form">
@Localizer["Language:"] <select name="culture"
asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
</select>
</form>
</div> <div class="container body-content">
@RenderBody()
<hr />
<footer>
<div class="row">
<div class="col-md-6">
<p>&copy; - Localization.StarterWeb</p>
</div>
<div class="col-md-6 text-right">
@await Html.PartialAsync("_SelectLanguagePartial")
</div>
</div>
</footer>
</div> [HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears() }
); 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.

DotNETCore 学习笔记 全球化和本地化的更多相关文章

  1. DotNETCore 学习笔记 WebApi

    API Description Request body Response body GET /api/todo Get all to-do items None Array of to-do ite ...

  2. DotNETCore 学习笔记 MVC视图

    Razor Syntax Reference Implicit Razor expressions <p>@DateTime.Now</p> <p>@DateTim ...

  3. DotNETCore 学习笔记 宿主

    Hosting -------------------------------------------------------------------------- Setting up a Host ...

  4. DotNETCore 学习笔记 依赖注入和多环境

    Dependency Injection ------------------------------------------------------------------------ ASP.NE ...

  5. DotNETCore 学习笔记 配置

    Configuration var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(); var config ...

  6. DotNETCore 学习笔记 日志

    Logging --------------------------------------------------------------------------------------- Impl ...

  7. DotNETCore 学习笔记 异常处理

    Error Handling public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIISP ...

  8. DotNETCore 学习笔记 路由

    Route ------------------------------------------constraint------------------------------------------ ...

  9. DotNETCore 学习笔记 Startup、中间件、静态文件

    Application Startup Startup Constructor - IHostingEnvironment - ILoggerFactory ConfigureServices - I ...

随机推荐

  1. 【算法】 string 转 int

    [算法] string 转 int 遇到的一道面试题, 当时只写了个思路, 现给出具体实现 ,算是一种比较笨的实现方式 public class StringToInt { /// <summa ...

  2. Ubuntu16.04安装Zabbix

    基于Zabbix+MySQL+Apache(可选) apt-get install php7.0-bcmath php7.0-xml php7.0-mbstring安装Zabbix所需的几个PHP模块 ...

  3. 用IIS防止mdb数据库被下载(转载)

    原网址:http://www.cnblogs.com/kingreatwill/p/4224433.html 第一种方法:要求网站管理人员具体asp编程经验.因为现在的销售虚拟主机的系统,已经为用户建 ...

  4. 了解游戏编程与 AI

    噫语系列... 闲话 最近在重写我的一个 QQ 群机器人项目,并尝试将它改成更通用的结构,以方便在未来加入对 Wechat 和 Telegram 的支持. 在查资料的过程中,发现很多人认为一个群内多人 ...

  5. 成为IT精英,我奋斗7年【转】

    这些日子 我一直在写一个实时操作系统内核,已有小成了,等写完我会全部公开,希望能够为国内IT的发展尽自己一份微薄的力量.最近看到很多学生朋友和我当年一样没 有方向 ,所以把我的经历写出来与大家共勉,希 ...

  6. Daily Scrum 11.01

    全队进展速度很快,11月伊始都完成了初步的工作.交由负责整合工作的毛宇开始调试整合. Member Today's task  Tomorrow's task 李孟 task 616 测试 (活动) ...

  7. Week9 Teamework from Z.XML-Scenario testing

    关于场景测试 About Scenario testing   一.关于用户(About Personas) 1 我们如何预期我们的用户对我们的软件的使用 (How do we expect diff ...

  8. 201621044079WEEK06-接口、内部类

    作业06-接口.内部类 1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 注1:关键词与内容不求多 ...

  9. stap用法

    sudo stap -g submit_bio.stp -D MAXACTION=100000 kern_path_locked lookup_one_len filename_create --&g ...

  10. perf 对两个map是否重叠的判断,以及函数map_groups__fixup_overlappings代码逻辑

    该标题可以抽象出来的问题是:两个前开后闭的区间 rangeA 和 rangeB,如何判断这两个区间是否重叠.这个问题在内核中非常重要,虚拟地址空间的划分需要它,perf中map_group的构建也需要 ...