Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 get a 404 status code back. No other Get actions exist on this controller. Shouldn't this work?

public class FooController : ApiController
{
    public Foo Get(string username)
    {
      return _service.Get<Foo>(username);
    }
}
like image 508
Suedeuno Avatar asked May 19 '15 15:05

Suedeuno


1 Answers

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 mapped as foo and the optional id parameter is mapped to {username}. As you don't have a Get action method with a parameter called id a 404 is returned.

To fix this you can either call the API method by changing the URL to be explicit about the parameter name:

http://{domain}/api/foo?username={username}

Or you could change your parameter name in your action method:

public Foo Get(string id)
{
    var foo = _service.Get<Foo>(username);
    return foo;
}

Or you could change your route to accept a username:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{username}",
    defaults: new { username = RouteParameter.Optional }
);
like image 140
petelids Avatar answered Oct 22 '22 12:10

petelids