REST webapi URI GET with string instead of id not routing as expected

爱⌒轻易说出口 提交于 2019-12-30 09:37:21

问题


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


来源:https://stackoverflow.com/questions/30329724/rest-webapi-uri-get-with-string-instead-of-id-not-routing-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!