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. Linux用户态程序计时方式详解[转]

    转自: http://www.cnblogs.com/clover-toeic/p/3845210.html 前言 良好的计时器可帮助程序开发人员确定程序的性能瓶颈,或对不同算法进行性能比较.但要精确 ...

  2. 【C#】 RBAC 权限框架

    [C#] RBAC 权限框架 一. 名词解释 1. 用户 : 登录的账号, 和角色挂钩,可拥有多个角色 2. 角色 : 账号所属的角色, 和权限挂钩,可拥有多个权限 3. 权限 : 角色拥有的操作权限 ...

  3. (原)Android到IOS开发的转换(一)

    序)闲扯几句 很早就想入手ios开发,但是一直没有机会,个人没有水果机器,上个公司上班的那台mac mini虽然就在我身边,灰都有一层了,但是一直没有机会开机学习下,因为事多,自上一篇文章后,离职后, ...

  4. 「日常训练」Single-use Stones (CFR476D2D)

    题意(Codeforces 965D) $w$表示河的宽度,$l$表示青蛙所能跳的最远的距离,第二行的$w-1$个元素表示离河岸为$i$的地方有$a[i]$个石头,一个石头被踩两次,问最多有多少只青蛙 ...

  5. 【个人笔记】关于C++小数的处理

    无论是C-Style还是C++-Style的输出,小数都会四舍五入.如果想要截断两种比较好的方法.第一种:利用sscanf输出成字符串,再人为地putchar().第二种:已知钦定保留6位小数,那么可 ...

  6. C变量之间的转换

    int main(){ //定义了三个变量分别是abc ab的值分别是5跟8 c没有赋值  把b的值给c 把a的值给b 把c的值给a 形成了一个ab值得转换: int a=5; int b=8; in ...

  7. CPU拓扑结构

    本篇旨在认识一下以下三种CPU拓扑结构分别是什么: Symmetric multiprocessing (SMP) Non-uniform memory access (NUMA) Simultane ...

  8. ZooKeeper完全分布式安装与配置

    Apache ZooKeeper是一个为分布式应用所设计开源协调服务,其设计目是为了减轻分布式应用程序所承担的协调任务.可以为用户提供同步.配置管理.分组和命名服务. 1.环境说明 在三台装有cent ...

  9. MySQL性能分析和优化-part 1

    MySQL性能优化 平时我们在使用MySQL的时候,怎么评估系统的运行状态,怎么快速定位系统瓶颈,又如何快速解决问题呢? 本文总结了多年来MySQL优化的经验,系统介绍MySQL优化的方法. OS性能 ...

  10. 简单的素数问题(C++)

    [问题描述] 已知三个素数的和为 n ,正整数 n 由键盘输入,计算并输出这三个素数乘积的最大值. [代码展示] # include<iostream>using namespace st ...