Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Web API - Routes for composite keys

I'm struggling to work out the routing configuration needed to support the following simple scenario:

http..service/api/objects/key1/key2

I feel like I've tried everything.

The biggest problem is that whenever it looks like I've cracked it, I find that

http..service/api/objects/key1 

gets routed to the parameterless IQueryable Get.

like image 334
Luke Puplett Avatar asked Jul 05 '12 11:07

Luke Puplett


1 Answers

I think I've nailed it.

routes.MapHttpRoute(
    name: IQueryableObjectsApiRouteName,
    routeTemplate: "api/objects",
    defaults: new { controller = "objects" }
);

routes.MapHttpRoute(
    name: ObjectsApiRouteName,
    routeTemplate: "api/objects/{siteId}/{assetId}",
    defaults: new { controller = "objects", siteId = "", assetId = "" }
);

I need to setup two explicit routes to each controller with composite keys. The default values for the keys are "", which I detect in the controller and throw my own 404.

It works for me. I can go to lunch now.

like image 143
Luke Puplett Avatar answered Sep 29 '22 18:09

Luke Puplett