[英]MVC ActionLink triggers a RouteConstraint?
我的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" }
);
}
}
為了確保用戶名存在,我有一個名為UserNameRouteConstraint()
的RouteConstraint
所有這些操作都是在我的用戶表中進行的簡單查找,如果找到了該用戶,則返回true。
到目前為止,一切順利,此工程效果很好!
現在; 我在用戶Area
中的視圖具有以下代碼行
@Html.ActionLink("More information", "details", new {id = product.Guid})
這一行導致UserNameRouteConstraint()
被調用。
如何以及為什么!? 如果我以純HTML
編寫鏈接(請參見下面的示例),則效果很好,但是我想盡可能地MVC
原則。
<a href="/username/Products/details/@product.Guid">More information</a>
有什么方法可以防止RouteConstraint
調用嗎?
每當生成路由時,都會處理約束。
您可以添加此檢查來停止約束,具體取決於約束是在處理傳入請求還是從ActionLink
類的函數生成URL:
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if(routeDirection == RouteDirection.UrlGeneration)
return false;
...
}
當您在后台調用ActionLink
,它將創建一個RouteValueDictionary
並運行RouteCollection.GetVirtualPath()
。 這部分不是開源的,但是我對它如何工作的最好猜測是,它會根據每個路由的默認值和約束條件檢查生成的路由值字典的參數,直到找到匹配的路由。 因此,它會運行您的約束,因此您應該希望它運行您的約束,以免最終與錯誤的路線匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.