Asp.net-Mvc
MVC 路由錯誤:約束條目“長度”
我有一個名為 Account 的控制器,其操作具有以下簽名:
public ActionResult Verify(string userName, Guid authorisationToken);我創建了一個連結來呼叫此操作:
/Account/Verify/sachin13/409bdaaa-0b65-4bb8-8695-6e430323d8f8當我轉到此連結時,我收到以下錯誤:
The constraint entry 'Length' on the route with URL 'Account/{Verify}/{userName}/{authorisationToken}' must have a string value or be of a type which implements IRouteConstraint.這就是我的 RegisterRoutes 方法在 Global.asax 中的樣子:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ,// Parameter defaults new[] { "UI.Controllers" } ); routes.MapRoute( "AccountVerify", "Account/{Verify}/{userName}/{authorisationToken}", new { controller = "Account", action = "Verify", userName = "", authorisationToken = "" }, "UI.Controllers" ); }兩個問題:
- 我是否在做任何不尋常的事情,或者我的方法是否符合標準做法?
- 這裡有什麼問題?
謝謝,
薩欽
你應該改變
"UI.Controllers"至
new[] { "UI.Controllers" }在你的第二條路線。
如果您只指定一個字元串(而不是數組),那麼您會得到錯誤的
MapRoute函式重載 - 而不是MapRoute(RouteCollection, String, String, Object, String[])接受名稱空間列表作為最後一個參數,您會得到MapRoute(RouteCollection, String, String, Object, Object)它期望約束作為最後一個參數。字元串“UI.Controllers”不是正確的約束規範=>你得到錯誤。同樣正如@Pankaj 建議的那樣,您的自定義路由應該在預設之前進行,並且驗證應該沒有“{}”。
完整程式碼:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "AccountVerify", "Account/Verify/{userName}/{authorisationToken}", new { controller = "Account", action = "Verify", userName = "", authorisationToken = "" }, new [] { "UI.Controllers" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ,// Parameter defaults new[] { "UI.Controllers" } ); }