为什么我不能通过Web API路径调用正确的方法?
问题描述:
我有我的第一个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()
我在做什么错?
答
请注意基础上的反映,的WebAPI作品,这意味着你花括号{}瓦尔必须在方法相同的名字相匹配。
因此,为了匹配这个api/chart/{id}
你的方法必须声明是这样的:
[Route("api/chart/{chartId}"), HttpGet]
public IEnumerable<Chart> Get(int chartId)
return userId;
}
其中参数{id}
被chartId
取代。
另一种选择可能是:
[Route("api/chart/{id}"), HttpGet]
public IEnumerable<Chart> Get(int id)
return userId;
}
如果您想了解更多关于这个路由规则这里是类似的职位上这一点;
Spot on。谢谢Dalorzo。 – Flippsie 2014-09-29 08:27:48