ASP.NET Core 请求本地化选项

Posted

技术标签:

【中文标题】ASP.NET Core 请求本地化选项【英文标题】:ASP.NET Core Request Localization Options 【发布时间】:2016-12-24 16:55:27 【问题描述】:

这是我的自定义请求文化提供程序,如果 url 中没有指定文化(例如 http://sypalo.com/ru 或 http://sypalo.com/en),它将返回“en”作为默认文化。 我的想法是以用户浏览器中默认的语言显示网站,所以我正在寻找一种方法来确定它并返回它而不是:return Task.FromResult(new ProviderCultureResult("en", "en"));

services.Configure<RequestLocalizationOptions>(options =>

    var supportedCultures = new List<CultureInfo>
    
        new CultureInfo("en"),
        new CultureInfo("ru")                            
    ;

    options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;

    options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
                        
        var pathSegments = context.Request.Path.Value.Split('/');
        if (pathSegments.Count() > 0)
        if (supportedCultures.Select(x => x.TwoLetterISOLanguageName).Contains((pathSegments[1])))
            return Task.FromResult(new ProviderCultureResult(pathSegments[1], pathSegments[1]));
       return Task.FromResult(new ProviderCultureResult("en", "en"));
   ));
);

【问题讨论】:

【参考方案1】:

您可以从当前的Request 获取Accept-Language 标头并设置默认语言。你的代码应该是这样的:

services.Configure<RequestLocalizationOptions>(options =>

    //...

    options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
                        
       //...
       var userLangs = context.Request.Headers["Accept-Language"].ToString();
       var firstLang = userLangs.Split(',').FirstOrDefault();
       var defaultLang = string.IsNullOrEmpty(firstLang) ? "en" : firstLang;
       return Task.FromResult(new ProviderCultureResult(defaultLang, defaultLang));
   ));
);

【讨论】:

非常感谢 Adem,这正是我想要的!【参考方案2】:

另一种通过框架调用(ASP.NET Core)获取 Accept-Language 标头的方法:

HttpContext.Request.GetTypedHeaders().AcceptLanguage

【讨论】:

不要忘记按优先级排序语言q,例如OrderByDescending(x =&gt; x.Quality ?? 1).【参考方案3】:

在你的public class Startup

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    //...

    app.Use((context, next) =>
    
        //get client prefered language
        var userLangs = context.Request.Headers["Accept-Language"].ToString();
        var firstLang = userLangs.Split(',').FirstOrDefault();

        //set allowed alanguage
        var lang = "en"; //default
        switch (firstLang)
        
            case "hy": //allowed
            case "ru": //allowed
                lang = firstLang; 
                break;
            default:
                //client language not supported
                lang = "en"; //use our default
                break;
        

        //switch culture
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

        //save for later use
        context.Items["ClientLang"] = lang;
        context.Items["ClientCulture"] = Thread.CurrentThread.CurrentUICulture.Name;
        
        // Call the next delegate/middleware in the pipeline
        return next();
    );

    //... then goes app.UseMvc etc..


【讨论】:

【参考方案4】:

作为附加选项,这是一个完整的解决方案:Handle culture in route (URL) via RequestCultureProviders

作为一个选项,这里是 CustomRequestCultureProvider 的简化代码:

options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>

    var lang = context.Request.GetTypedHeaders().AcceptLanguage.FirstOrDefault()?.Value.Value ?? Constants.Languages.EN_US;

    return Task.FromResult(new ProviderCultureResult(lang, lang));

));

【讨论】:

以上是关于ASP.NET Core 请求本地化选项的主要内容,如果未能解决你的问题,请参考以下文章

本地 Javascript Fetch Post 请求失败,调用 ASP.NET Core 2.2 Web API。 CORS 已启用

[Core]Asp.Net Core中的各种过滤器(授权资源操作结果异常)

ASP.NET Core 模型绑定错误消息本地化

[Core]Asp.Net Core中的各种过滤器(授权资源操作结果异常)

ASP.NET Core 6.0 本地化

ASP.NET Core 6.0 本地化