2011-07-04 26 views
0

我正在尝试将constraint添加到controller。我可能有这个完全错误的,但我的理解是,如果route不匹配,那么应该不是调用constructor方法?添加MVC约束仍然调用控制器方法

这里是我的路线:

routes.MapRoute(
    "UserProfile", 
    "UserProfile/{userName}", 
    new { controller = "UserProfile", action = "Index" }, 
    new { userName = @"[a-zA-Z]+" } 
); 

所以,我认为,因为我问了userName,当我打的网址mywebsite/UserProfile应该不匹配?请有一些纠正我的想法,如果有人可以帮忙,以获得route而不是调用constructor方法,因为userName丢失,这将是很好的。

回答

0

如果您只注册了此路由,那么控制器将不会被此路由实例化或命中。我假设你正在观察的行为是由于你也已经离开了默认路由注册将匹配的请求/UserProfileUserProfile控制器和Index行动的事实:

routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

所以删除此默认路由你应该没问题。你的路由定义应该如下所示:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     "UserProfile", 
     "UserProfile/{userName}", 
     new { controller = "UserProfile", action = "Index" }, 
     new { userName = @"[a-zA-Z]+" } 
    ); 
} 
+0

使用Phil Haacks路由调试器,当我删除'Default'路由时失败。我从Route Debugger的输出中得到一个'NO MATCH',即使我指定了'userName' –

+0

@Neil Knight,你的控制器叫做UserProfileController还是只有'UserProfile'并且它包含一个'Index'动作? –

+0

它被称为'UserProfileController'并且包含'Index'动作。这个问题似乎与正则表达式有关。当我为''*'改变'+'时,它就起作用了。 –