通过RequestCultureProviders处理路线(URL)中的区域性 [英] Handle culture in route (URL) via RequestCultureProviders

查看:70
本文介绍了通过RequestCultureProviders处理路线(URL)中的区域性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个适当的requestCultureProviders,以使用以下路由模板处理来自AspNetCore WebApp中路由的区域性: http//url.domain/{culture}/{controller}/{action}

I would like create a proper requestCultureProviders to handle the culture from the route in AspNetCore WebApp with the following route template: http//url.domain/{culture}/{controller}/{action}

示例:

  • http://myWebSite.com/en/Home/Index
  • http://myWebSite.com/fr/Home/Index

我在第一个脏/草稿解决方案下面发布了消息.

I post Below my first dirty/draft solution.

推荐答案

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add the localization services to the services container
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        // Add framework services.
        services.AddMvc()
            // Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            // Add support for localizing strings in data annotations (e.g. validation messages) via the
            // IStringLocalizer abstractions.
            .AddDataAnnotationsLocalization();

        // Configure supported cultures and localization options
        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("en"),
                new CultureInfo("fr")
            };

            // State what the default culture for your application is. This will be used if no specific culture
            // can be determined for a given request.
            options.DefaultRequestCulture = new RequestCulture(culture: "fr", uiCulture: "fr");

            // You must explicitly state which cultures your application supports.
            // These are the cultures the app supports for formatting numbers, dates, etc.
            options.SupportedCultures = supportedCultures;

            // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
            options.SupportedUICultures = supportedCultures;

            // You can change which providers are configured to determine the culture for requests, or even add a custom
            // provider with your own logic. The providers will be asked in order to provide a culture for each request,
            // and the first to provide a non-null result that is in the configured supported cultures list will be used.
            // By default, the following built-in providers are configured:
            // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
            // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
            // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
            options.RequestCultureProviders.Insert(0, new RouteCultureProvider(options.DefaultRequestCulture));
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(localizationOptions.Value);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "InternationalizationDefault",
                template: "{culture=en}/{controller=Home}/{action=Index}/{id?}");
        });
        // ...
    }
}

RouteCultureProvider.cs

public class RouteCultureProvider : IRequestCultureProvider
{
    private CultureInfo defaultCulture;
    private CultureInfo defaultUICulture;

    public RouteCultureProvider(RequestCulture requestCulture)
    {
        this.defaultCulture = requestCulture.Culture;
        this.defaultUICulture = requestCulture.UICulture;
    }

    public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        //Parsing language from url path, which looks like "/en/home/index"
        PathString url = httpContext.Request.Path;

        // Test any culture in route
        if (url.ToString().Length <= 1)
        {
            // Set default Culture and default UICulture
            return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
        }

        var parts = httpContext.Request.Path.Value.Split('/');
        var culture = parts[1];

        // Test if the culture is properly formatted
        if (!Regex.IsMatch(culture, @"^[a-z]{2}(-[A-Z]{2})*$"))
        {
            // Set default Culture and default UICulture
            return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
        }

        // Set Culture and UICulture from route culture parameter
        return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(culture, culture));
    }
}

添加资源/视图/View.en.resx 文件 键/值对HelloWorld: Hello World !

添加资源/视图/View.fr.resx 文件 键/值对HelloWorld: Bonjour tout le monde !

View.cshtml

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

<h2>Localizer["HelloWorld"]</h2>

EtVoilà:)

这篇关于通过RequestCultureProviders处理路线(URL)中的区域性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆