.net 核心 3.1 localization/culture 作者 URL - localhost/en/area?/controller/action

.net core 3.1 localization/culture by URL - localhost/en/area?/controller/action

我一直在为 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
            });

用于在 cookie 中保存用户选择的 HomeController

        [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);
        }

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();
});

您可以使用以下代码

配置服务:

 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));

语言路由约束:

 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 and here。希望对您有所帮助