ASP NET Web API路由模板

时间:2013-02-01 01:46:29

标签: asp.net asp.net-web-api routes asp.net-web-api-routing

我有一个名为Agency的实体,后面跟着apis

GET     http://localhost:37331/api/agency?start=1&limit=10&status=1
GET     http://localhost:37331/api/agency/2
POST    http://localhost:37331/api/agency 
PUT     http://localhost:37331/api/agency
DELETE  http://localhost:37331/api/agency/4
POST    http://localhost:37331/api/agency/activate/3
POST    http://localhost:37331/api/agency/deactivate/3
GET     http://localhost:37331/api/agency/types

我使用的路线模板是

        config.Routes.MapHttpRoute(
            name: "ControllerActionIdApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { },
            constraints: new { id = @"\d+" }
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerActionApi",
            routeTemplate: "api/{controller}/{action}"
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerIdApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { },
            constraints: new { id = @"\d+" }
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerApi",
            routeTemplate: "api/{controller}"
        );

显然第二和第三之间存在歧义。我有一个解决方法,将id放入查询字符串

GET     http://localhost:37331/api/agency?id=2
DELETE  http://localhost:37331/api/agency?id=4

我认为一定有聪明的方法。你能就此提出建议吗?

由于

2 个答案:

答案 0 :(得分:7)

路线按顺序匹配。您的约束:第3条路线上的新{id = @“\ d +”}未获得查看,因为第二条路线将始终获胜。

所以换掉你的第二和第三条路线。

始终将最具选择性的路线放在最顶层。

    config.Routes.MapHttpRoute(
        name: "ControllerActionIdApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { },
        constraints: new { id = @"\d+" }
    );
    //

    config.Routes.MapHttpRoute(
        name: "ControllerIdApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { },
        constraints: new { id = @"\d+" }
    );
    //
    config.Routes.MapHttpRoute(
        name: "ControllerActionApi",
        routeTemplate: "api/{controller}/{action}"
    );
    //
    config.Routes.MapHttpRoute(
        name: "ControllerApi",
        routeTemplate: "api/{controller}"
    );

答案 1 :(得分:0)

试试这个

routeTemplate: "api/{controller}/{action}/{id}"