Reputation: 26291
Is it possible to use custom routes handling code?
For example client requests server on http://server.com/api/v1/json/profile/
and my code calls ApiController
, MyAction
action with parameters version=1
, format=json
, action=profile
.
Upvotes: 1
Views: 103
Reputation: 3493
Something like this? You'll have to use a different parameter name for action so you don't have a conflict with the controller action.
.MapRoute("name", "api/v{version}/{format}/{_action}", new { controller = "ApiController", action = "MyAction" });
EDIT made version work the way you wanted.
Upvotes: 1
Reputation: 101604
I would start off by renaming the "action" parameter to something else otherwise the route is going to get very confusing (maybe call it purpose?). Also, I believe something like the following would work:
routes.MapRoute(
// name of your route
"MyRoute",
// route template
"api/v{version}/{format}/{purpose}",
// default route values
new {
controller = "ApiController",
action = "MyAction",
},
// constraints placed on parameters (make sure they are valid)
new {
version = @"^\d+$", // number only (can also include decimals)
format = @"^(json|text|xml)$", // if you want filtering...
}
);
Then:
public ApiController : Controller
{
public ActionResult MyAction(Int32 version, String format, String purpose)
{
throw new NotImplementedException();
}
}
Upvotes: 1