ASP.NET MVC 4 Routes - controller/id vs controller/action/id

后端 未结 1 1277
慢半拍i
慢半拍i 2020-12-09 04:33

I\'m trying to add a route to the default one, so that I have both urls working:

  1. http://www.mywebsite.com/users/create
  2. http://www.m
相关标签:
1条回答
  • 2020-12-09 04:47

    The key is to put more specific routes first. So put the "Book" route first. Edit I guess you also need a constraint to only allow numbers to match the "id" part of this route. End edit

    routes.MapRoute(
        name: "Book",
        url: "books/{id}",
        defaults: new { controller = "users", action = "Details" },
        constraints: new { id = @"\d+" }
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "users", action = "Index", id = UrlParameter.Optional }
    );
    

    And ensure that the "id" parameter in your "Details" action is an int:

    // "users" controller
    public ActionResult books(int id)
    {
        // ...
    }
    

    This way, the "Books" route will not catch a URL like /users/create (since the second parameter is reqiured to be a number), and so will fall through to the next ("Default") route.

    0 讨论(0)
提交回复
热议问题