Sue*_*uno 5 c# asp.net rest asp.net-web-api
我有以下示例,其中请求是,http://{domain}/api/foo/{username}
但是我得到了404状态代码。该控制器上不存在其他Get操作。这不行吗?
public class FooController : ApiController
{
public Foo Get(string username)
{
return _service.Get<Foo>(username);
}
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,您的路线将如下所示:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
当您访问 url 时http://{domain}/api/foo/{username}
,控制器被映射为foo
,可选id
参数被映射到{username}
. 由于您没有id
返回带有名为404的参数的 Get 操作方法。
要解决此问题,您可以通过将 URL 更改为明确参数名称来调用 API 方法:
http://{domain}/api/foo?username={username}
Run Code Online (Sandbox Code Playgroud)
或者您可以在操作方法中更改参数名称:
public Foo Get(string id)
{
var foo = _service.Get<Foo>(username);
return foo;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以更改路线以接受username
:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{username}",
defaults: new { username = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5715 次 |
最近记录: |