ASP.NET Core MVC可以支持基于路由的区域化,这意味着我们可以在不同的区域中为不同的语言提供不同的视图和资源。下面是实现基于路由的区域化的步骤:
1.首先在Startup.cs文件中添加以下代码:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc() .AddViewLocalization() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResources)); });
2.接下来,在Program.cs文件中添加以下代码:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
config.AddEnvironmentVariables();
})
.ConfigureServices(services =>
{
services.Configure
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider());
});
services.AddSingleton();
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.AddRouting(options =>
{
options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
});
})
.Configure(app =>
{