我可能有一个蹩脚的问题,但我在一个网址中路由多个控制器时遇到了一些麻烦。所以我的问题是如何使用这样的网址:
GET http://foo.com/API/Devices/2/Parameters/2
最终device
和parameters
都是控制器,而数字是ID。我有每个控制器但是如何处理它们,将它们路由到适当的控制器?
任何方向看?
更新
只是为了澄清我最终使用的解决方案并遵循以下答案。
路由代码段:
config.Routes.MapHttpRoute(
name: "DeviceCommandsControllerHttpRoute",
routeTemplate: "api/devices/{deviceId}/commands/{id}",
defaults: new { controller = "devicecommands", id = RouteParameter.Optional }
);
Controller snippet:
[HttpGet]
public DeviceCommand GetById(int id, int deviceId)
{ ... }
最后是网址:
GET http://localhost:49479/api/Devices/2/Commands/1
答案 0 :(得分:9)
我现在正在处理类似的需求,我有以下路线结构:
public static void RegisterRoutes(HttpRouteCollection routes) {
routes.MapHttpRoute(
"UserRolesHttpRoute",
"api/users/{key}/roles",
new { controller = "UserRoles" });
routes.MapHttpRoute(
"AffiliateShipmentsHttpRoute",
"api/affiliates/{key}/shipments",
new { controller = "AffiliateShipments" });
routes.MapHttpRoute(
"ShipmentStatesHttpRoute",
"api/shipments/{key}/shipmentstates",
new { controller = "ShipmentStates" });
routes.MapHttpRoute(
"AffiliateShipmentShipmentStatesHttpRoute",
"api/affiliates/{key}/shipments/{shipmentKey}/shipmentstates",
new { controller = "AffiliateShipmentShipmentStates" });
routes.MapHttpRoute(
"DefaultHttpRoute",
"api/{controller}/{key}",
new { key = RouteParameter.Optional });
}
我认为你可以根据这一点弄清楚如何实现你的。