如何处理这种类型的Web API 2路由方案?

时间:2015-11-12 16:36:03

标签: asp.net-mvc asp.net-web-api2 url-routing asp.net-mvc-routing asp.net-web-api-routing

如何定义一组允许我处理这两种URI请求的路由(或修改我的控制器)?请注意,我可以修改我的类和路由,但我无法更改URI的结构。

示例1 URI 正确路由WidgetsController

api / widgets / {widget id}

示例2 URI 路由错误WidgetsController。我希望它路由到WidgetActionController

api / widgets / {widget id} / widgetaction / {widget action id}

这是我的控制器

Public Class WidgetsController

    Inherits ApiController

    ' GET api/widgets/{widget id}
    Public Function [Get](id as integer) As Widget
        Return DataAccess.GetWidgetByID(id)
    End Function

End Class

Public Class WidgetActionController

    Inherits ApiController

    ' GET api/widgets/{widget id}/widgetaction/{action}
    Public Function [Get](id as integer, action as integer) As Boolean
        'Get Widget By ID
        'Perform {action} on Widget    
    End Function

End Class

以下是我的路线:

config.Routes.MapHttpRoute("Data",
                 "api/{controller}/{id}/{year}/{month}/{day}",
                 New With {Key .id = RouteParameter.[Optional],
                 .year = RouteParameter.[Optional],
                 .month = RouteParameter.[Optional],
                 .day = RouteParameter.[Optional]})

config.Routes.MapHttpRoute("WidgetAction",
                           "api/widgets/{id}/widgetaction/{action}", 
                           New With {Key .controller = "WidgetAction"})

2 个答案:

答案 0 :(得分:1)

路由是特定于订单的。在这种情况下,您唯一需要做的就是在通用路由之前放置更具体的路由。

 config.Routes.MapHttpRoute("WidgetAction",
                       "api/widgets/{id}/widgetaction/{action}", 
                       New With {Key .controller = "WidgetAction"})

 config.Routes.MapHttpRoute("Data",
             "api/{controller}/{id}/{year}/{month}/{day}",
             New With {Key .id = RouteParameter.[Optional],
             .year = RouteParameter.[Optional],
             .month = RouteParameter.[Optional],
             .day = RouteParameter.[Optional]})

问题是,Data路由始终匹配WidgetAction路由可能匹配的每种情况。第一个匹配总是获胜,使您的第二个路由成为无法访问的执行路径。如果您颠倒订单,如果网址不包含widgets作为第二个细分,widgetaction作为第四个细分,则第一个路线将不匹配,从而允许检查Data路线

答案 1 :(得分:0)

我找不到使用标准路由的方法,所以我将其转储并转到属性路由。我发现这篇文章非常有用

http://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI