【问题标题】:.net core 3.1 localization/culture by URL - localhost/en/area?/controller/action.net core 3.1 通过 URL 进行本地化/文化 - localhost/en/area?/controller/action
【发布时间】:2020-01-28 01:47:13
【问题描述】:

我一直在为 Core 3.1 本地化而苦苦挣扎,但我现在终于用他们的新行为做到了(令人惊讶的是,他们的文档没有针对新的变化进行更新)。

话虽如此,我似乎找不到一种基于 URL 制作文化的好方法,例如:https://localhost/en/area?/controller/action

注意:我几天前找到了一个解决方案,但它不适用于身份(身份对我的工作至关重要)

我需要你的帮助。

当前设置:-

配置服务

            services.AddLocalization();

            services.AddMvc()
                .AddMvcLocalization()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(SharedResource));
                });


            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en"),
                        new CultureInfo("ar")
                    };

                options.DefaultRequestCulture = new RequestCulture("en");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });

配置

            var supportedCultures = new[]
            {
                new CultureInfo("en"),
                new CultureInfo("ar"),
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

HomeController 将用户选择保存在 cookie 中

        [HttpPost]
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );

            return LocalRedirect(returnUrl);
        }

【问题讨论】:

    标签: asp.net .net asp.net-mvc asp.net-core asp.net-core-3.1


    【解决方案1】:

    在RequestLocalizationOptions中配置RouteDataRequestCultureProvider:

    services.Configure<RequestLocalizationOptions>(options =>
    {
        // ...
    
        options.RequestCultureProviders.Insert(0, 
            new RouteDataRequestCultureProvider { Options = options } 
        );
    });
    

    如果您使用的是控制器,请将端点配置为使用 {culture} 路由值:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{culture=en}/{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
    

    【讨论】:

    【解决方案2】:

    您可以使用以下代码

    配置服务:

     List<CultureInfo> supportedCultures = new List<CultureInfo>() {
    
                new CultureInfo("en"),
                new CultureInfo("ar"),
        };
    
    
            services.Configure<RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new RequestCulture("ar");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                options.RequestCultureProviders = new List<IRequestCultureProvider>
                    {
                        new QueryStringRequestCultureProvider(),
                        new CookieRequestCultureProvider()
                    };
    
            });
            services.Configure<RouteOptions>(options =>
            {
                options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
            });
    
    services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix));
    

    LanguageRouteConstraint:

     public class LanguageRouteConstraint : IRouteConstraint
    {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return true;
        }
    }
    

    配置

       app.UseRequestLocalization();
       app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areaRoute",
                    template: "area/{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
                routes.MapRoute(
                    name: "LocalizedDefault",
                    template: "{lang:lang=ar}/{controller=Home}/{action=Index}/{id?}"
                );
    
                routes.MapRoute(
                  name: "default",
                  template: "{*catchall}",
                  defaults: new { controller = "Home", action = "RedirectToDefaultLanguage" });
            });
    

    控制器:

     [Route("{lang}/[controller]")]
     [Route("[controller]")]
    

    引用自 here 和 here。我希望这会有所帮助

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多