.Net Core全球化多语言

参照:ASP.NET Core 全球化和本地化

步骤如下:

  • 后台中的本地化。

  Startup.cs中注册服务并制定Resource文件的位置。注意:这里的位置不仅仅应用到Web层,如Infrastruce、DAL、Service层都有自己相应的不同语言的话,在已用泛型时,都会使用泛型所在层的该位置文件。

services.AddLocalization(options =>
            {
                options.ResourcesPath = "Resources";
            });
            // Configure supported cultures and localization options
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("zh-CN")
                };
                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                //options.DefaultRequestCulture = new RequestCulture(culture: "zh-CN", uiCulture: "zh-CN");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });

 

  

使用:

public class AboutController : Controller
    {
        private readonly IStringLocalizer<AboutController> _localizer;

        public AboutController(IStringLocalizer<AboutController> localizer)
        {
            _localizer = localizer;
        }

        [HttpGet]
        public string Get()
        {
            return _localizer["About Title"];
        }
    }

 

  • DataAnnotations 本地化。

  在程序中添加一个冗余的SharedResource.cs类,该类用于公共资源文件,不再使用各自的资源文件。

  

//仅用于SharedResource文件的地址映射
namespace BasicFramework.Infrastructure.Localizations
{
    public class SharedResource
    {
    }
}

    在同一层中在Resources文件夹下增加Localizations.SharedResource.zh-CN.resx文件,注意该文件名为SharedResource.cs类移除其默认命名空间后的地址。

    至Startup.cs中添加AddDataAnnotationsLocalization,并指定使用统一的资源文件。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

  使用

public class RegisterViewModel
{
    [Required(ErrorMessage = "The Email field is required.")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required(ErrorMessage = "The Password field is required.")]
    [StringLength(8, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [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; }
}

 

  • 视图中本地化

  在_ViewImports.cshtml中引入。注:最后一句为Tag,与本地化无关。

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer L
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

  使用:

@L["Add Info"]

 

  • 我的使用

  SharedResource.cs文件及Localizations.SharedResource.zh-CN.resx文件都放在了Infrastructure层,其他层调用:

        private readonly IStringLocalizer _localizer;
        protected ILogger _logger;
        protected BaseService()
        {
            _localizer = IocManager.GetService<IStringLocalizer<SharedResource>> ();
            _logger = IocManager.GetService<ILogger<BaseService>>();
        }

   视图中也直接注入共享文件:

@using BasicFramework.Infrastructure.Localizations
@using Microsoft.AspNetCore.Mvc.Localization

@inject IHtmlLocalizer<SharedResource> L

 

posted @ 2018-06-12 14:09  邑尘  阅读(638)  评论(0编辑  收藏  举报