ASP.NET Core WebAPI實現本地化(單資源文件)

在Startup ConfigureServices 註冊本地化所須要的服務AddLocalizationConfigure<RequestLocalizationOptions>git

public void ConfigureServices(IServiceCollection services)
        {
            services.AddLocalization();
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-us"),
                    new CultureInfo("zh-cn")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-us", uiCulture: "en-us");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                options.RequestCultureProviders = new IRequestCultureProvider[] { new RouteDataRequestCultureProvider { IndexOfCulture = 1, IndexofUiCulture = 1 } };
            });
            services.Configure<RouteOptions>(options =>
            {
                options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
            });
            services.AddControllers();
        }

在Startup.cs類的Configure 方法中添加請求本地化中間件。github

var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(localizeOptions.Value);

RequestCultureProvider 它使用簡單的委託來肯定當前的本地化區域性,固然咱們還能夠經過RequestCultureProvider自定義源的請求區域信息好比說配置文件或者數據庫都是能夠的.或者說咱們能夠選用默認的一些方式讓咱們去獲取到當前區域.數據庫

ASP.NET Core 本地化默認向咱們提供了四個方式,可用於肯定正在執行的請求的當前區域性:app

  • QueryStringRequestCultureProvider
  • CookieRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider
  • CustomRequestCultureProvider

以下所示我將經過路由的方式,去肯定當前區域ide

public class RouteDataRequestCultureProvider : RequestCultureProvider
    {
        public int IndexOfCulture;
        public int IndexofUiCulture;

        public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException(nameof(httpContext));
            string uiCulture;

            string culture = uiCulture = httpContext.Request.Path.Value.Split('/')[IndexOfCulture];

            var providerResultCulture = new ProviderCultureResult(culture, uiCulture);

            return Task.FromResult(providerResultCulture);
        }
    }

經過以下代碼片斷實現IRouteConstraint對路由作相應的約束ui

public class LanguageRouteConstraint : IRouteConstraint
    {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {

            if (!values.ContainsKey("culture"))
                return false;

            var culture = values["culture"].ToString();
            return culture == "en-us" || culture == "zh-cn";
        }
    }

添加區域資源文件this

注入IStringLocalizer<T>StringLocalizer將經過傳遞的共享資源(T)的值映射到資源文件,而後將本地化根據字符串的名稱從資源文件返回響應的值3d

[Route("{culture:culture}/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly IStringLocalizer<Resource> localizer;
        public HomeController(IStringLocalizer<Resource> localizer)
        {
            this.localizer = localizer;
        }
        public string Get()
        {
            return localizer["Home"];
        }
    }

以下圖所示
code

Reference

https://github.com/hueifeng/BlogSample/tree/master/src/LocalizationSingleResx中間件

相關文章
相關標籤/搜索