Asp.net 如何将当前路由中的特定值自动添加到所有生成的链接中?
我在URL中有如下站点文化:Asp.net 如何将当前路由中的特定值自动添加到所有生成的链接中?,asp.net,asp.net-mvc,asp.net-mvc-2,asp.net-mvc-routing,Asp.net,Asp.net Mvc,Asp.net Mvc 2,Asp.net Mvc Routing,我在URL中有如下站点文化: routes.MapRoute( "Default", "{language}/{controller}/{action}/{id}", languageDefaults, languageConstraints) 在自定义MVCHTTPTHandler的帮助下,它就像一个魔咒,根据路由值在每个请求上设置当前线程的UI区域性。我的问题是如何将当前请求中的语言路由值自动添加到所有传出链接?例如,当请求page/EN/Foo/Ba
routes.MapRoute(
"Default",
"{language}/{controller}/{action}/{id}",
languageDefaults,
languageConstraints)
在自定义MVCHTTPTHandler的帮助下,它就像一个魔咒,根据路由值在每个请求上设置当前线程的UI区域性。我的问题是如何将当前请求中的语言路由值自动添加到所有传出链接?例如,当请求page/EN/Foo/Bar时,我希望
<%=Html.ActionLink(
"example link",
MVC.Home.Index()) %>
要自动生成与此相同的结果,请执行以下操作:
<%=Html.ActionLink(
"example link",
MVC.Home.Index()
.AddRouteValue(
"language",
this.ViewContext.RouteData.Values["language"]) %>
当然,所有其他帮助程序(如BeginForm()等)也是如此。在我当前的代码库中,已经有超过1000次使用这些帮助程序,并且每次都需要.AddRouteValue是非常脆弱的,因为一些开发人员会忘记100%确定地使用它
我希望唯一的解决方案不是为所有内容创建自定义Html帮助程序?它应该保留route中定义的所有值,并自动显示在
RoutedData
中,除非您将其设置为其他内容。尝试在没有T4MVC的情况下创建链接,或检查路由定义。像这样的东西对我很管用:
routes.MapRoute("Default with language", "{lang}/{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
}, new { lang = "de|fr" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
lang = "en",
});
+
+
奇怪,非常奇怪:这是我所期望的工作方式,但事实并非如此。现在,我创建了一个香草测试项目,您是对的,它在您编写时确实有效。我的项目中一定有什么东西破坏了这种行为(第一个嫌疑犯是T4MVC)。T4MVC不是原因,而是一个纯粹而简单的错误:我在母版页上有语言更改链接。在呈现这些链接时,可用语言的列表被循环,在循环过程中,当前路径被错误地更改。
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
MvcHandler handler = Context.Handler as MvcHandler;
if (handler == null)
return;
string lang = (string)handler.RequestContext.RouteData.Values["lang"];
CultureInfo culture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
}
<%: Html.ActionLink("About us", "Detail", "Articles", new { @type = ArticleType.About }, null) %>