gpt4 book ai didi

asp.net - ASP NET Web API 路由模板

转载 作者:行者123 更新时间:2023-12-04 23:57:57 25 4
gpt4 key购买 nike

我有一个名为 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}"
);

显然,第二和第三之间存在歧义。我确实有一个将 id 放入查询字符串的解决方法
GET     http://localhost:37331/api/agency?id=2
DELETE http://localhost:37331/api/agency?id=4

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

谢谢

最佳答案

路由按顺序匹配。您的约束条件:第三条路线上的 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}"
);

关于asp.net - ASP NET Web API 路由模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com