Nested resources in ASP.net MVC 4 WebApi

前端 未结 4 596
深忆病人
深忆病人 2020-12-02 07:09

Is there a better way in the new ASP.net MVC 4 WebApi to handle nested resources than setting up a special route for each one? (similar to here: ASP.Net MVC support for Nest

4条回答
  •  萌比男神i
    2020-12-02 08:01

    Sorry, I have updated this one multiple times as I am myself finding a solution.

    Seems there is many ways to tackle this one, but the most efficient I have found so far is:

    Add this under default route:

    routes.MapHttpRoute(
        name: "OneLevelNested",
        routeTemplate: "api/{controller}/{customerId}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    This route will then match any controller action and the matching segment name in the URL. For example:

    /api/customers/1/orders will match:

    public IEnumerable Orders(int customerId)
    

    /api/customers/1/orders/123 will match:

    public Order Orders(int customerId, int id)
    

    /api/customers/1/products will match:

    public IEnumerable Products(int customerId)
    

    /api/customers/1/products/123 will match:

    public Product Products(int customerId, int id)
    

    The method name must match the {action} segment specified in the route.


    Important Note:

    From comments

    Since the RC you'll need to tell each action which kind of verbs that are acceptable, ie [HttpGet], etc.

提交回复
热议问题