REST webapi URI GET with string instead of id, not routing as expected
I have the following example where the request is http://{domain}/api/foo/{username}
, but I am returning a 404 status code. There are no other Get actions on this controller. Shouldn't this work?
public class FooController : ApiController
{
public Foo Get(string username)
{
return _service.Get<Foo>(username);
}
}
source to share
By default, your route will look something like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
When you visit the url http://{domain}/api/foo/{username}
, the controller is displayed as foo
, and the optional parameter is id
mapped to {username}
. Since you don't have a Get action method with a parameter id
, 404 is returned.
To fix this, you can call the API method by changing the URL to explicitly specify the parameter name:
http://{domain}/api/foo?username={username}
Or you can change the parameter name in your action method:
public Foo Get(string id)
{
var foo = _service.Get<Foo>(username);
return foo;
}
Or you can change your route to take username
:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{username}",
defaults: new { username = RouteParameter.Optional }
);
source to share