哪个请求文化提供者是更好的选择

时间:2019-05-14 04:45:20

标签: asp.net-web-api asp.net-core localization internationalization

我正在.NET Core Web API中进行本地化,并停留在选择请求区域性提供程序选项上。

Microsoft从文档中提供了三个默认的区域性提供程序,它们是自动配置的。

QueryStringRequestCultureProvider
CookieRequestCultureProvider
AcceptLanguageHeaderRequestCultureProvider

除了上述三个之外,我们还可以创建一个自定义区域性提供程序,但是我的问题是,哪个选项更安全,更一致。

1 个答案:

答案 0 :(得分:0)

所有取决于您的应用程序架构,就我个人而言,我更喜欢定制路由值请求区域性提供商。

它将为您提供干净的网址,例如:

  

http://www.example.com/en-US/

如何创建它:

首先为文化参数创建全局路线模型约定:

public class CultureTemplateRouteModelConvention : IPageRouteModelConvention
    {
        public void Apply(PageRouteModel model)
        {
            var selectorCount = model.Selectors.Count;
            for (var i = 0; i < selectorCount; i++)
            {
                var selector = model.Selectors[i];
                model.Selectors.Add(new SelectorModel
                {
                    AttributeRouteModel = new AttributeRouteModel
                    {
                        Order = -1,
                        Template = AttributeRouteModel.CombineTemplates(
                      "{culture?}",
                      selector.AttributeRouteModel.Template),
                    }
                });
            }
        }
    }

然后将其添加到剃须刀页面选项:

services.AddMvc()
        .AddRazorPagesOptions(o => {
            o.Conventions.Add(new CultureTemplateRouteModelConvention());
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        });

然后创建RouteValueRequestCultureProvider:

public class RouteValueRequestCultureProvider : IRequestCultureProvider
    {
        private readonly CultureInfo[] _cultures;

        public RouteValueRequestCultureProvider(CultureInfo[] cultures)
        {
            _cultures = cultures;
        }

        /// <summary>
        /// get {culture} route value from path string, 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns>ProviderCultureResult depends on path {culture} route parameter, or default culture</returns>
        public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
        {
            var defaultCulture = "en";

            var path = httpContext.Request.Path;

            if (string.IsNullOrWhiteSpace(path))
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            var routeValues = httpContext.Request.Path.Value.Split('/');
            if (routeValues.Count() <= 1)
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            if (!_cultures.Any(x => x.Name.ToLower() == routeValues[1].ToLower()))
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            return Task.FromResult(new ProviderCultureResult(routeValues[1]));
        }
    }

然后将其添加到文化提供商列表中:

services.Configure<RequestLocalizationOptions>(ops =>
            {
                ops.DefaultRequestCulture = new RequestCulture("en");
                ops.SupportedCultures = mySupportedCultures;
                ops.SupportedUICultures = mySupportedUICultures;

                // add RouteValueRequestCultureProvider to the beginning of the providers list. 
                ops.RequestCultureProviders.Insert(0, 
                    new RouteValueRequestCultureProvider(cultures));
            });