MVC RouteLocalization 难以重定向到正确的前缀

MVC RouteLocalization difficulty redirecting to correct prefix

我在我的网站上使用 RouteLocalization.Mvc 库进行翻译,但在不使用默认区域性(英语)时遇到一些困难。

我的网站已本地化为西班牙语,当我的浏览器语言设置为英语时,所有路由都可以正常工作 - 我得到的是英语的无前缀路由和预期的西班牙语前缀 /es/ 路由。

然而,当我将浏览器的文化设置为西班牙语时,我在未加前缀的路由上获得了翻译页面,但我真正想要的前缀是(以我的关于页面为例):

接受语言:英语

接受语言:西班牙语

我打算重定向到正确的前缀,但似乎不知道该怎么做。

var config = new Configuration()
{
    DefaultCulture = "en",
    AcceptedCultures = new HashSet<string> { "en", "es" },
    AddCultureAsRoutePrefix = true,
    AddTranslationToSimiliarUrls = true,
    AttributeRouteProcessing = AttributeRouteProcessing.AddAsNeutralRoute
};

// translations omitted

CultureSensitiveHttpModule.GetCultureFromHttpContextDelegate = Localization.DetectCultureFromBrowserUserLanguages(acceptedCultures, defaultCulture);
GlobalFilters.Filters.Add(new CultureSensitiveActionFilterAttribute());

任何帮助将不胜感激!!!

您想要的设置如下:

  • 英语本地化路线(无前缀)
  • 西班牙语本地化路线(带前缀)
  • 没有中性路线

我认为你的英文路线实际上是中性路线(因为AttributeRouteProcessing.AddAsNeutralRoute)。

尝试将 AddCultureAsRoutePrefix 设置为 false,将 AttributeRouteProcessing 设置为 AddAsDefaultCultureRoute。然后调用 TranslateInitialAttributeRoutes().

这会将不带前缀的属性路由添加为本地化的英语路由。文档中的一些信息:

First you have to decide how the initial attribute routes, which are intercepted by RouteLocalization, should be processed. There are a few possibilities that can be choosen via the Configuration.AttributeRouteProcessing property.

If your attribute routes for example are English be default, you could define that every attribute route should be added as localized route for English culture. You would therefore set the DefaultCulture to "en" and AttributeRouteProcessing to AddAsDefaultCultureRoute.

调用 TranslateInitialAttributeRoutes 后,您可以将 AddCultureAsRoutePrefix 设置回 true,然后开始翻译您的西班牙路线。