[英]API multiple Get methods and routing
我有一个只有Get Methods的控制器
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 }
);
有人启发我我做错了什么吗?
路由引擎希望绑定到名为id
的变量,如路由配置中所定义:
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}", //<--- here {id} means bind to parameter named 'id'
defaults: new { id = RouteParameter.Optional }
);
在您的操作中, GetMachinesByKey(string key)
参数被命名为key
,因此框架不会为您连接这些点。
您可以在查询字符串中传递参数,因此使用/api/{contorller}/GetMachiesByKey/?key=HP
形式的URL将正确绑定(您可能需要更改路由配置,因为这不会传递id
参数,当前配置将是预期的)。
另外,我相信您可以使用属性路由指定动作的路由 。 这允许您用一个属性装饰您的action方法,该属性告诉框架如何解决路由,例如:
[Route("<controller>/GetMachinesByKey/{key}")]
public IEnumerable<Device> GetMachinesByKey(string key)
使用RoutePrefix和Route属性。
[RoutePrefix("api/device")]
public class DeviceController : ApiController
{
List<Device> machines = new List<Device>();
[HttpGet]
[Route("Machines")]
public IEnumerable<Device> GetAllMachines()
{
//do something
return machines;
}
[HttpGet]
[Route("Machines/{id:int}")]
public IEnumerable<Device> GetMachineByID(int id)
{
//do something
return machines;
}
[HttpGet]
[Route("Machines/{key}")]
public IEnumerable<Device> GetMachinesByKey(string key)
{
//do something
return machines;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.