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