我希望我的api有两个GET方法,一个是通过路径参数访问的Route:
api/people/{personId}
另一个是通过查询参数访问的Route:
api/people?text=something
但如果我放入以下代码:
// GET: api/people/{personId}
[Route("api/people/{personId}")]
[HttpGet]
public HttpResponseMessage Get(long personId)
{
}
// GET: api/people?text=something
[Route("api/people")]
[HttpGet]
public HttpResponseMessage Get(string text)
{
}
然后尝试打开/api/people/1,提示格式错误。当我尝试打开/api/people?text=something时,它可以正常工作。
我只定义了默认路由:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我该如何让它们都起作用?定义一下,如果是路径参数就去第一个,如果是查询参数就去第二个?
long
改成int
会发生什么?(出于好奇)。虽然是个好问题,但我还不确定答案。从这段代码看,我认为应该不会有任何问题。 - user1017882long
还是int
,结果都是一样的。 - Vítor Martins