通过RequestCultureProviders处理路径(URL)中的文化

我想创建一个正确的requestCultureProviders来处理来自AspNetCore WebApp中路由的文化,并使用以下路由模板: http // url.domain / {culture} / {controller} / {action}

示例:

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

我发布了我的第一个脏/草案解决方案。

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, eg Index.fr.cshtml .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) // Add support for localizing strings in data annotations (eg validation messages) via the // IStringLocalizer abstractions. .AddDataAnnotationsLocalization(); // Configure supported cultures and localization options services.Configure(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, ie 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>(); 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 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(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, @"^[az]{2}(-[AZ]{2})*$")) { // Set default Culture and default UICulture return Task.FromResult(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName)); } // Set Culture and UICulture from route culture parameter return Task.FromResult(new ProviderCultureResult(culture, culture)); } } 

使用键/值对HelloWorld: Hello World !添加Resources / Views / View.en.resx文件HelloWorld: Hello World !

使用键/值对HelloWorld: Bonjour tout le monde !添加Resources / Views / View.fr.resx文件HelloWorld: Bonjour tout le monde !

View.cshtml中

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

Localizer["HelloWorld"]

EtVoilà:)