ASP.NET核心请求本地化选项

时间:2016-08-17 21:39:16

标签: c# asp.net asp.net-mvc asp.net-core

这是我的自定义请求文化提供程序,它返回" en"作为默认文化,如果在网址中未指定文化(例如http://sypalo.com/ruhttp://sypalo.com/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"));
   }));
});

4 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分:10)

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

HttpContext.Request.GetTypedHeaders().AcceptLanguage

答案 2 :(得分:1)

在您的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":
                lang = "hy"; //allowed
                break;
            case "ru":
                lang = "ru"; //allowed
                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..

}

答案 3 :(得分:0)

作为一个附加选项,这是一个完整的解决方案: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));

}));