0
votes

Is it possible to have the following actions mapped with only one single route?

public class SimpleDataController : ApiController
{
    // GET /SimpleData
    public List<MyObject> Get(){ return new List<MyObject>();};

    // GET /SimpleData/4
    public MyObject Get(int objectId){ return new MyObject{Id = objectId);};

    // GET /SimpleData/4/ObjectsForId
    public List<MySubObject> ObjectsForId(int objectId){ return new List<MySubObject>();};

    // GET /SimpleData/4/ObjectsForId/3
    public MySubObject ObjectsForId(int objectId, int subObjectId){ return new MySubObject();};
}   

In my WebApiConfig.cs I've added the following code to the routes:

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

This works for:

  • GET /SimpleData/4/ObjectsForId and GET /SimpleData/4/ObjectsForId/3

For GET /SimpleData I get the following error:

The requested resource does not support http method 'GET'.

For GET /SimpleData/4 I get:

Multiple actions were found that match the request: Get on type Controllers.SimpleDataController ObjectsForId on type Controllers.SimpleDataController

I've already tried to set the default for action to 'Get' which will work for the example above, but will fail for POST, PUT and DELETE as it will also check for an action named 'Get'. Is there any trick I don't know about?

I don't want to create new mappings for each controller.

1

1 Answers

0
votes

You need to make paramter id also optional. Otherwise is the parameter always required and the route GET /SimpleData will not work.

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