How to handle hierarchical routes in ASP.NET Web API?

Haris Hasan picture Haris Hasan · May 28, 2012 · Viewed 23.3k times · Source

Currently I have two controllers

1 - Parent Controller

2 - Child Controller

I access my Parent Controller like this

someurl\parentcontroller

Now I want to access my children controller like this

someurl\parentcontroller\1\childcontroller

This last url should return all the children of a particular parent.

I have this route currently in my global.asax file

routes.MapHttpRoute ("Route1", "{controller}/{id}", new { id = RouteParameter.Optional });

I am not sure how can I achieve my parent\id\child hierarchy.. How should I configure my routes to achieve this? Ideas?

Answer

Abhijit-K picture Abhijit-K · May 28, 2012

Configure the routes as below. The {param} is optional (use if you need):

routes.MapHttpRoute(
           name: "childapi",
           routeTemplate: "api/Parent/{id}/Child/{param}",
           defaults: new { controller = "Child", param = RouteParameter.Optional }
  );

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

Then call the child APi as /api/Parent/1/child The parent can be called simple as /api/Parent/

The child controller:

    public class ChildController : ApiController
    {     
        public string Get(int id)
        {
          //the id is id between parent/{id}/child  
          return "value";
        }
        .......
    }