开发者

Url routing not working as expected

This is my RegisterRoutes method in 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 }
    开发者_如何学Go        );

            routes.MapRoute("ListBooks",
              "Home/Books/{id}",
              new { controller = "Home", action = "Books" },
              new { id = @"\d{2}" });


        }

As you can see in the constraint I have specified that the id should be compulsory there of 2 digits. But having specified this, even though I enter just a single digit book id it all still works out pretty well. Can anybody tell me what is wrong in this?


Your default route should be placed after the other routes, otherwise it would take the precedence.


Your constraint works as expected and url is not matched to the "ListBooks" route. But, if you look closer to the "Default" route, it has the same signature as the "ListBooks" one - but without constraint. So "Default" handles that single digit id url. In this case, your route order does not matter, as the "Default" will catch single digit id url anyways.


Try this

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


        routes.MapRoute("ListBooks", 
          "Home/Books/{id}", 
          new { controller = "Home", action = "Books" }, 
          new { id = @"\d{2}" }); 

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

    } 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜