4

我有一个名为 Agency 的实体,具有以下 api

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

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

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

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

谢谢

4

2 回答 2

7

路由按顺序匹配。您的约束:第三条路线上的 new { 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}"
    );
于 2013-02-01T10:08:40.893 回答
0

试试这个

routeTemplate: "api/{controller}/{action}/{id}"
于 2013-02-01T07:23:16.620 回答