.Net Core全球化多語言

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

步驟以下:ide

  • 後臺中的本地化。

  Startup.cs中註冊服務並制定Resource文件的位置。注意:這裏的位置不單單應用到Web層,如Infrastruce、DAL、Service層都有本身相應的不一樣語言的話,在已用泛型時,都會使用泛型所在層的該位置文件。ui

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

 

  

使用:spa

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 本地化。code

  在程序中添加一個冗餘的SharedResource.cs類,該類用於公共資源文件,再也不使用各自的資源文件。htm

  

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

    在同一層中在Resources文件夾下增長Localizations.SharedResource.zh-CN.resx文件,注意該文件名爲SharedResource.cs類移除其默認命名空間後的地址。blog

    至Startup.cs中添加AddDataAnnotationsLocalization,並指定使用統一的資源文件。資源

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

  使用get

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,與本地化無關。string

@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
相關文章
相關標籤/搜索