【发布时间】:2014-05-22 21:27:33
【问题描述】:
我有一个只有 Get 方法的控制器
public class DeviceController : ApiController
{
List<Device> machines = new List<Device>();
public IEnumerable<Device> GetAllMachines()
{
//do something
return machines;
}
[HttpGet]
public IEnumerable<Device> GetMachineByID(int id)
{
//do something
return machines;
}
[HttpGet]
public IEnumerable<Device> GetMachinesByKey(string key)
{
//do something
return machines;
}
}
我希望能够通过 URL 访问这些并取回数据
../api/{contorller}/GetAllMachines
../api/{contorller}/GetMachineByID/1001
../api/{contorller}/GetMachiesByKey/HP (machines exist)
当我在 IE 开发人员模式 (f12) 中运行前两个时,我得到 Json,显示所有机器和机器 1001。但是当我运行 GetMachinesByKey/HP 时,我得到 404 错误。
我的 WebApiConfig 也是这样的
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
有人告诉我我做错了什么吗?
【问题讨论】:
-
看看这篇文章,或许能帮到你。 asp.net/web-api/overview/web-api-routing-and-actions/…
-
我认为路由引擎希望绑定到路由配置中定义的名为
id的变量;您的操作参数被命名为key,因此框架不会为您连接这些点。 -
@DaveParsons 是对的。
标签: c# asp.net-web-api asp.net-web-api-routing