I am trying to build a web API which would accept 2 parameters. However, upon calling the API it always hits the method without any parameters. I followed the instructions in here, and can't figure why it won't work.
The request I send using the 'PostMaster' Chrome extension : http://localhost:51403/api/test/title/bf
For the above request, I expect the first method to be hit, but the second method is being reached.
The method within the controller are :
// Get : api/test/type/slug
public void Get(string type,string slug){
//Doesn't reach here
}
// Get : api/test
public void Get() {
// Reaches here even when the api called is GET api/test/type/slug
}
The webApiConfig hasn't been changed much, except that it accepts 2 parameters :
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id1}/{id2}",
defaults: new { id1 = RouteParameter.Optional, id2 = RouteParameter.Optional }
);
}
My understanding from the documentation is that the webapiconfig doesn't have to be changed. Here's the error that I get
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:51403/api/test/title/bf'.",
"MessageDetail":"No action was found on the controller 'test' that matches the request."}
In order for the routing engine to route the request to the right Action, it looks for the method whose parameters match the names in the route first.
In other words, this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id1}/{id2}",
defaults: new { id1 = RouteParameter.Optional, id2 = RouteParameter.Optional }
);
matches:
public void Get(string id1, string id2) {}
but not:
public void Get(string type, string slug) {}
If you wanted to, this would have also worked:
http://localhost?type=weeeee&slug=herp-derp
which would have matched
public void Get(string type, string slug)