.Net Core 本地化&全球化 实践

介绍:

  所有有关本地化的数据获取,都是从统一的一个资源文件中获取

1.创建虚拟类、资源文件,用于作为本地化数据的获取源 

 2.Configure localization:支持view、data annotation、mvc

            services.AddLocalization(options => options.ResourcesPath = "Resources");            
            services.AddMvc()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                    factory.Create(typeof(SharedResource));
            }).AddMvcLocalization()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

3.Localization middleware:

默认排序为

  1. QueryStringRequestCultureProvider
  2. CookieRequestCultureProvider
  3. AcceptLanguageHeaderRequestCultureProvider

可以更改顺序,甚至添加一个自定义区域性提供程序

            var supportedCultures = new[]{"zh-CN","en-US"};

            app.UseRequestLocalization(cultureOptions=>
            {
                cultureOptions.AddSupportedCultures(supportedCultures)
                .AddSupportedUICultures(supportedCultures)
                .SetDefaultCulture(supportedCultures[0]);
                cultureOptions.FallBackToParentCultures = true;
            });        

  

4.注册本地化服务,用于全局调用(单一实例)

            services.AddSingleton<IStringLocalizer>((sp) =>
            {
                var sharedLocalizer = sp.GetRequiredService<IStringLocalizer<SharedResource>>();
                return sharedLocalizer;
            });

  

5.使用

view使用

@using Microsoft.AspNetCore.Mvc.Localization
@inject Microsoft.Extensions.Localization.IStringLocalizer localizer

<p>@Localizer["Use this area to provide additional information."]</p>

  

controller使用

public class BookController : Controller
    {
        private readonly IStringLocalizer _localizer;

        public BookController(IStringLocalizer localizer)
        {
            _localizer = localizer;
        }

        public IActionResult Hello(string name)
        {
            ViewData["Message"] = _localizer["<b>Hello</b><i> {0}</i>", name];

            return View();
        }

  

DataAnnotations 错误消息自动添加,

因为Configure localization步骤中,已经添加了支持AddDataAnnotationsLocalization

6.视图,默认语言可自配置

以编程方式设置区域性

 

共享视图:Views/Shared/_SelectLanguagePartial.cshtml 

@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.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();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home" 
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" 
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">
            @Localizer["Language:"]
       </label> 
        <select name="culture"
          onchange="this.form.submit();"
          asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
        </select>
    </form>
</div>    

  

Views/Shared/_SelectLanguagePartial.cshtml 文件添加到了布局文件的 footer 部分,使它将可供所有视图使用:

<div class="container body-content" style="margin-top:60px">
    @RenderBody()
    <hr>
    <footer>
        <div class="row">
            <div class="col-md-6">
                <p>© @System.DateTime.Now.Year - Localization</p>
            </div>
            <div class="col-md-6 text-right">
                @await Html.PartialAsync("_SelectLanguagePartial")
            </div>
        </div>
    </footer>
</div>

  

将Language的设置保存至cookie

[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);
}

  

 7.优化

  

猜你喜欢

转载自www.cnblogs.com/panpanwelcome/p/10148688.html