[英]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. 我有以下示例,其中请求是
http://{domain}/api/foo/{username}
但我得到404状态代码。 No other Get actions exist on this controller. 此控制器上不存在其他Get操作。 Shouldn't this work?
这不应该工作吗?
public class FooController : ApiController
{
public Foo Get(string username)
{
return _service.Get<Foo>(username);
}
}
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}
. 当您访问URL
http://{domain}/api/foo/{username}
,控制器将映射为foo
,可选的id
参数将映射到{username}
。 As you don't have a Get action method with a parameter called id
a 404 is returned. 由于您没有带有名为
id
的参数的Get操作方法,因此返回404。
To fix this you can either call the API method by changing the URL to be explicit about the parameter name: 要解决此问题,您可以通过更改URL以显示有关参数名称来调用API方法:
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
: 或者您可以更改路线以接受
username
:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{username}",
defaults: new { username = RouteParameter.Optional }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.