0
我有我的第一个Web API工作,但即使当我调用它并传递一个id时,也会被路由到没有参数的方法。为什么我不能通过Web API路径调用正确的方法?
这里是我的控制器代码:
public class ChartController : ApiController
{
Chart[] _charts = new Chart[]
{
new Chart { Name = "Chart 1" },
new Chart { Name = "Chart 2" },
new Chart { Name = "Chart 3" }
};
// GET api/chart
[Route("api/chart")]
public IEnumerable<Chart> Get()
{
return _charts;
}
// GET api/chart/{id}
[Route("api/chart/{id}")]
public IEnumerable<Chart> Get(int chartId)
{
Chart[] charts = new Chart[]
{
Charts.Database.ChartsDB.GetChart(chartId)
};
return charts;
}
}
这是我在我的Global.asax路由
RouteTable.Routes.MapHttpRoute(
name: "ChartApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
这是我的请求的URI
http://localhost:42311/api/chart
而且结果
[
{
"Name": "Chart 1"
},
{
"Name": "Chart 2"
},
{
"Name": "Chart 3"
}
]
当我更改URI到
http://localhost:42311/api/chart/1
我得到相同的结果,因为这两个呼叫路由到
public IEnumerable<Chart> Get()
我在做什么错?
Spot on。谢谢Dalorzo。 – Flippsie 2014-09-29 08:27:48