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. vue循环绑定v-model

    直接上代码 结构: <repayInput v-if="formData" v-for="(item, index) in formData" :isPw ...

  2. Qt 汽车仪表再次编写,Widget,仪表显示,绘制界面

    感谢某网友提供UI让我练练手,上目前的效果 还在晚上,代码等后面在贴出来,就是出来显摆一下

  3. python 基础篇 16 递归和二分数查找与编码补充回顾

    编码回顾补充: 回顾编码问题:        编码相当于密码本,关系到二进制与看懂的文字的的对应关系.    最早期的密码本:        ascii码:只包含英文字母,数字,特殊字符.       ...

  4. LB

    LB(LBaaS)及Load Balance as a Service是 Neutron 提供的一项高级网络服务. LBaaS 允许租户在自己的网络中创建和管理 load balancer,load ...

  5. 剑指offer-跳台阶08

    题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果). class Solution: def jumpFloor(self, ...

  6. 问题 A: 完数

    问题 A: 完数 时间限制: 1 Sec  内存限制: 32 MB提交: 252  解决: 178[提交][状态][讨论版][命题人:外部导入] 题目描述 求1-n内的完数,所谓的完数是这样的数,它的 ...

  7. windows下git hub的GUI软件配置与使用

    转载自:http://www.cnblogs.com/haore147/p/3618930.html   1. 安装两个软件 1 2 1. git的命令行程序--git for windows:htt ...

  8. HDU 4571 Travel in time(最短路径+DP)(2013 ACM-ICPC长沙赛区全国邀请赛)

    Problem Description Bob gets tired of playing games, leaves Alice, and travels to Changsha alone. Yu ...

  9. 给Python初学者的一些编程建议

    Python是一种非常富有表现力的语言.它为我们提供了一个庞大的标准库和许多内置模块,帮助我们快速完成工作.然而,许多人可能会迷失在它提供的功能中,不能充分利用标准库,过度重视单行脚本,以及误解Pyt ...

  10. sqlite sql语句关键字GROUP BY的理解

    第一遍看GROUP BY的介绍时,没看懂. SQLite 的 GROUP BY 子句用于与 SELECT 语句一起使用,来对相同的数据进行分组.在 SELECT 语句中,GROUP BY 子句放在 W ...