REST webapi URI GET with string instead of id not

2020-03-21 10:20发布

问题:

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);
    }
}

回答1:

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 }
);