[英]MVC ActionLink triggers a RouteConstraint?
I have this simple User Area
in my MVC 4
project. 我的
MVC 4
项目中有一个简单的用户Area
。
public class UserAreaRegistration : AreaRegistration
{
public override string AreaName { get { return "User"; } }
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("User_Constraint",
"{userName}/{controller}/{action}/{id}",
new { userName = string.Empty, controller = "Products", action = "Index", id = UrlParameter.Optional },
new { userName = new UserNameRouteConstraint() },
new[] { "T2b.Web.Areas.User.Controllers" }
);
}
}
To make sure the User Name exists I have a RouteConstraint
called UserNameRouteConstraint()
为了确保用户名存在,我有一个名为
UserNameRouteConstraint()
的RouteConstraint
All this does is a simple lookup in my users table and return true if the user has been found. 所有这些操作都是在我的用户表中进行的简单查找,如果找到了该用户,则返回true。
So far so good, this construction works fine! 到目前为止,一切顺利,此工程效果很好!
Now; 现在; My view in the User
Area
has the following line of code 我在用户
Area
中的视图具有以下代码行
@Html.ActionLink("More information", "details", new {id = product.Guid})
This single line causes the UserNameRouteConstraint()
to be called.... 这一行导致
UserNameRouteConstraint()
被调用。
How and why!? 如何以及为什么!? If I write the link in plain
HTML
(see example below) it works well, but I want to keep to the MVC
Principles as close as possible. 如果我以纯
HTML
编写链接(请参见下面的示例),则效果很好,但是我想尽可能地MVC
原则。
<a href="/username/Products/details/@product.Guid">More information</a>
Is there any way to prevent the RouteConstraint
call? 有什么方法可以防止
RouteConstraint
调用吗?
Whenever routes are generated the constraints are processed. 每当生成路由时,都会处理约束。
You can add this check to stop the constraint depending on whether the constraint is handling an incoming request or generating a URL from a function like ActionLink
: 您可以添加此检查来停止约束,具体取决于约束是在处理传入请求还是从
ActionLink
类的函数生成URL:
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if(routeDirection == RouteDirection.UrlGeneration)
return false;
...
}
When you call ActionLink
behind the scenes it creates a RouteValueDictionary
and runs RouteCollection.GetVirtualPath()
. 当您在后台调用
ActionLink
,它将创建一个RouteValueDictionary
并运行RouteCollection.GetVirtualPath()
。 This part is not open source but my best guess as to how it works is that it checks the parameters of the generated route value dictionary against the defaults and constraints of each route until it finds one that matches. 这部分不是开源的,但是我对它如何工作的最好猜测是,它会根据每个路由的默认值和约束条件检查生成的路由值字典的参数,直到找到匹配的路由。 Because of this it runs your constraints, and you should want it to run your constraints so that it doesn't end up matching to the wrong route.
因此,它会运行您的约束,因此您应该希望它运行您的约束,以免最终与错误的路线匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.