5

我可能有一个蹩脚的问题,但我在一个 URL 中路由多个控制器时遇到了一些困难。所以我的问题是如何使用这样的网址:

GET http://foo.com/API/Devices/2/Parameters/2

最终deviceparameters所有控制器和数字都是 ID。我对它们每个都有控制器,但是如何处理它们,将它们路由到正确的控制器?

有什么方向可以看吗?

更新:
只是为了澄清我最终使用的解决方案并遵循以下答案。

路由片段:

config.Routes.MapHttpRoute(
            name: "DeviceCommandsControllerHttpRoute", 
            routeTemplate: "api/devices/{deviceId}/commands/{id}", 
            defaults: new { controller = "devicecommands", id = RouteParameter.Optional }
        );

控制器片段:

[HttpGet]
public DeviceCommand GetById(int id, int deviceId)
    { ... }

最后是网址:

GET http://localhost:49479/api/Devices/2/Commands/1
4

1 回答 1

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 });
}

我认为您可以在此基础上弄清楚如何实现您的。

于 2012-10-09T08:54:00.580 回答