DotNETCore 学习笔记 全球化和本地化
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>© - 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 学习笔记 全球化和本地化的更多相关文章
- DotNETCore 学习笔记 WebApi
API Description Request body Response body GET /api/todo Get all to-do items None Array of to-do ite ...
- DotNETCore 学习笔记 MVC视图
Razor Syntax Reference Implicit Razor expressions <p>@DateTime.Now</p> <p>@DateTim ...
- DotNETCore 学习笔记 宿主
Hosting -------------------------------------------------------------------------- Setting up a Host ...
- DotNETCore 学习笔记 依赖注入和多环境
Dependency Injection ------------------------------------------------------------------------ ASP.NE ...
- DotNETCore 学习笔记 配置
Configuration var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(); var config ...
- DotNETCore 学习笔记 日志
Logging --------------------------------------------------------------------------------------- Impl ...
- DotNETCore 学习笔记 异常处理
Error Handling public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIISP ...
- DotNETCore 学习笔记 路由
Route ------------------------------------------constraint------------------------------------------ ...
- DotNETCore 学习笔记 Startup、中间件、静态文件
Application Startup Startup Constructor - IHostingEnvironment - ILoggerFactory ConfigureServices - I ...
随机推荐
- Apache 配置说明
ServerRoot ServerRoot: The top of the directory tree under which the server's configuration, error, ...
- BI领军者之一Tableau试用浅谈
下图是最新的Gartner BI Magic Quadrant,其中领军者之一的Tableau表现的异常突出,执行力象限上直接甩开其它产品一条街,前瞻性象限上略微超越了MSBI,怀着无比的好奇心,特意 ...
- 【廖雪峰老师python教程】——装饰器
装饰器 # 一个函数装饰器的列子 def log(func): def wrapper(*args,**kwargs): print('Name=%s'%func.__name__) return f ...
- java 判断上午/下午
//结果为“0”是上午 结果为“1”是下午 public class GregorianTest { public static void main(String args[]) { Gregoria ...
- Tuxedo 通讯方式解析
本节根据tuxedo自带samples的例子,让其运行起来.并通过这个例子,深入的理解tuxedo的通讯方式. 进入tuxedo的安装目录,samples目录下自带了一些例子 [root@localh ...
- C++ 学习笔记之——文件操作和文件流
1. 文件的概念 对于用户来说,常用到的文件有两大类:程序文件和数据文件.而根据文件中数据的组织方式,则可以将文件分为 ASCII 文件和二进制文件. ASCII 文件,又称字符文件或者文本文件,它的 ...
- Python 3 学习笔记之——错误和异常
1. 语法错误 Python 的语法错误被称为解析错,语法分析器会指出出错的代码行,并且在最先找到的错误的位置标记一个小小的箭头. >>> while True File " ...
- linux mysql 链接数太小
Data source rejected establishment of connection, message from server: "Too many connections&q ...
- 【bzoj2764】[JLOI2011]基因补全 dp+高精度
题目描述 在生物课中我们学过,碱基组成了DNA(脱氧核糖核酸),他们分别可以用大写字母A,C,T,G表示,其中A总与T配对,C总与G配对.两个碱基序列能相互匹配,当且仅当它们等长,并且任意相同位置的碱 ...
- HDU 4776 Ants(Trie+优先队列)
Ants Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 327680/327680 K (Java/Others) Total S ...