代码之家  ›  专栏  ›  技术社区  ›  frank_lbt

ASP.NET核心:创建多语言翻译路线

  •  0
  • frank_lbt  · 技术社区  · 6 年前

    我想在ASP.NET核心,其中URL的翻译与此问题相同 How to create multilingual translated routes in Laravel

    其目的是翻译语言代码之后的url路径部分,并用用户语言生成url。

    例如:

    /fr/produit
    

    /en/product
    

    我有以下配置:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {   
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var translations = services.BuildServiceProvider().GetService<TranslationsDbContext>();
                var supportedCultures = translations.Cultures
                    .ToList()
                    .Select(x => new CultureInfo(x.Name))
                    .ToArray();
    
                options.DefaultRequestCulture = new RequestCulture(culture: "fr", uiCulture: "fr");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
    
                options.RequestCultureProviders = new RequestCultureProvider[]
                {
                    new RouteDataRequestCultureProvider()
                    {
                        RouteDataStringKey = "lang",
                        UIRouteDataStringKey = "lang",
                        Options = options
                    },
                    new CookieRequestCultureProvider(),
                    new AcceptLanguageHeaderRequestCultureProvider()
                }; 
            });
    
            services.Configure<RouteOptions>(options =>
            {
                options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
            }); 
    
            services.AddDbContextPool<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
    
            services.AddDbContext<TranslationsDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("TranslationsConnection")));
    
            services.AddIdentity<User, IdentityRole<Guid>>()
                .AddEntityFrameworkStores<ApplicationDbContext>();
    
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<IStringLocalizerFactory, EFStringLocalizerFactory>();
            services.AddScoped<IStringLocalizer, StringLocalizer>();
    
            services
                .AddMvc()
                .AddDataAnnotationsLocalization();
    
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            ApplicationDbContext dbContext, TranslationsDbContext translationsDbContext,
            UserManager<User> userManager, RoleManager<IdentityRole<Guid>> roleManager)
        { 
            app.UseRequestLocalization();
    
            app.UseWhen(
                context => !context.Request.Path.StartsWithSegments("/api"),
                a => a.UseLocalizedStatusCodePagesWithReExecute("/{0}/error/{1}")
            );
    
            app.UseResponseCompression();
    
            app.UseCookiePolicy();
    
            app.UseAuthentication();
    
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "localized",
                    template: "{lang:lang}/{controller=Home}/{action=Index}/{id?}"
                );
                routes.MapRoute(
                    name: "catchAll",
                    template: "{*catchall}",
                    defaults: new { controller = "Home", action = "RedirectToDefaultLanguage" }
                );
            });
        }
    }
    
    public class LanguageRouteConstraint : IRouteConstraint
    {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (!values.ContainsKey("lang"))
            {
                return false;
            }
    
            var lang = values["lang"].ToString();
    
            return lang == "fr" || lang == "en" || lang == "de";
        }
    }
    

    然而,经过许多研究,我发现我可以使用 IApplicationModelConvention

    0 回复  |  直到 6 年前