May 8, 2012

ASP.NET web api - multiple get does not work ?

So you've read and seen all there is on asp.net/webapi and your webapi service is running smoothly.
You follow rest and design guidelines of WEBAPI and place one GET, POST and all HTTP verbs.
Everything works, great cool.
For example in your CustomersController you have simple and single GET action which works just fine:
public string Get()  { 
return "Coolest customer controller";
 ; on url:   http://localhost/api/customers/get
and then you casually add another GET action:

public string Get(string what){
return "I'll be back";
}
And you run into problems:

404 - File or directory not found.



What a hack ?!

Ok, so you comment second Get and it works again. Aha!
But if you comment first Get and leave second it still works?
Actually if you step way back to your scenario with one GET and change action name like this:

public string GetDummy() {
thing still works on same url !

http://localhost/api/customers/get

What a  ... ?
You fervently start playing with different action names and it always works ?!
Now wait a sec... If you haven't played too much with MVC concept and you come from clean ASP.NET webforms arena you are by now probably in major piss of  state :)

Solution to your problem is tweaking routing engine. WEB API as HTTP skeleton of WCF is build on top of ASP.NET MVC and it uses its routing engine.

Catch is that guys from WEB API did not mean that average dude should have this basic routing setup out of the box in your WEB API template.

So go ahead and do it your self.
In your Global.asax.cs observe this part:


routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


; and tweak route so it accepts your action name like this:


routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


Now everything should work fine ...















No comments:

Post a Comment