I am setting up an ASP.NET MVC 4 Web API to accept requests from a 3rd party server, and I simply can’t figure out how to set the route mappings.
Assume the 3rd party server expects to get responses for:
http://[my_server]/authorize?user=[user name]&session=[session token]&item=[item]http://[my_server]/release?user=[user name]&session=[session token]
Alternatively, the requests can use a dedicated path, i.e.:
http://[my_server]/***api***/authorize?user=[user name]&session=[session token]&item=[item]http://[my_server]/***api***/release?user=[user name]&session=[session token]
I would like to be able to support both alternatives.
Additional requests, following the more traditional /controller/id form, should be implemented too, but I’d like to focus on the above (I’m not even sure that Web API is the way to go here).
I have written the following controller:
public class MyController : ApiController
{
[HttpGet]
[ActionName("authorize")]
public string Authorize(string user, string session, string item)
{
...
// return "OK" or "DENY";
}
[HttpGet]
[ActionName("release")]
public string Release(string user, string session)
{
...
return "OK";
}
}
and tried everything I could find in SO and elsewhere in WebAppConfig.Register, but I keep getting a 404 error when I try the request in the browser:
http://localhost:22332/api/authorize?user=ury&session=token&item=an_item
My question is, what do I have to do – specifically in WebAppConfig.Register and in the controller – in order to serve the above requests (assuming my test URL is correct…)?
After a few hours working on this and with a lot of help from the Route Debugger – Thanks Phil Haack! – I’ve found both the problem and the solution.
The problem: Route mapping matching is ordered, and
RouteTable.Routes, from which the app’s route mapping is initialized, contains quite a few of them. The request pattern I was looking for also matched some of these mappings (“authorize” was matched as a controller, for example).The solution: add “my” route mappings before the default mappings.
Yeah, right…
Since most operations are not supported on
HttpRouteCollection, the resulting code is a bit ugly, but it works:As long as “my” route mappings don’t match the default mappings (I made them specific enough not to), I’m all good – I think…