开发者

Adding an MVC Constraint still calls Controller method

I'm trying to add a constraint to a controller. I may have this completely wrong, but my understanding is that if the route doesn't match, then it shouldn't call the constructor method?

Here is my route:

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

So, I thought that because I'm asking for a userName, when I hit the url mywebsite/UserProfile it shouldn't match? Please can some correct me on my thinking, also if someone can help with regards to getting a route 开发者_如何学Gonot call the constructor method because the userName is missing that would be great too.


If you have only this route registered then the controller won't be instantiated or hit by this route. I assume that the behavior you are observing is due to the fact that you also have left the default route registration which will match a request /UserProfile to the UserProfile controller and the Index action:

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

So remove this default route and you should be OK. Your route definition should look like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜