具有多个参数的Web API路由

我正在尝试找出如何为以下Web API控制器进行路由:

public class MyController : ApiController { // POST api/MyController/GetAllRows/userName/tableName [HttpPost] public List GetAllRows(string userName, string tableName) { ... } // POST api/MyController/GetRowsOfType/userName/tableName/rowType [HttpPost] public List GetRowsOfType(string userName, string tableName, string rowType) { ... } } 

目前,我正在使用此路由到URL:

 routes.MapHttpRoute("AllRows", "api/{controller}/{action}/{userName}/{tableName}", new { userName= UrlParameter.Optional, tableName = UrlParameter.Optional }); routes.MapHttpRoute("RowsByType", "api/{controller}/{action}/{userName}/{tableName}/{rowType}", new { userName= UrlParameter.Optional, tableName = UrlParameter.Optional, rowType= UrlParameter.Optional }); 

但目前只有第一种方法(有2个参数)正在工作。 我是在正确的路线上,还是我的URL格式或路由完全错误? 路由对我来说似乎是黑魔法……

问题是您的api/MyController/GetRowsOfType/userName/tableName/rowType URL将始终与第一条路线匹配,因此永远不会达到第二条路线。

简单修复,首先注册您的RowsByType路由。

我看到WebApiConfig失控”,其中放置了数百条路线

相反,我个人更喜欢属性路由

你正在使它与POST和GET混淆

 [HttpPost] public List GetAllRows(string userName, string tableName) { ... } 

HttpPostGetAllRows

为什么不这样做:

 [Route("GetAllRows/{user}/{table}")] public List GetAllRows(string userName, string tableName) { ... } 

或更改为Route(“PostAllRows”和PostRows我认为你真的在做一个GET请求,所以我展示的代码应该适合你。来自客户端的调用将在ROUTE中为什么,所以它将使用GetAllRows找到你的方法,但方法本身,名称可以是你想要的任何东西,所以只要调用者匹配ROUTE中的URL,如果你真的想要,你可以为该方法输入GetMyStuff。

更新:

我实际上更喜欢explicitHTTP methods类型,我更喜欢将路径参数与方法参数匹配

 [HttpPost] [Route("api/lead/{vendorNumber}/{recordLocator}")] public IHttpActionResult GetLead(string vendorNumber, string recordLocator) { .... } 

(路径lead不需要匹配方法名称GetLead但是你想要在路径参数和方法参数上保留相同的名称,即使你可以改变顺序,例如将recordLocator放在vendorNumber之前,即使路线是相反的 -我不这样做,因为为什么让它看起来更混乱)。

奖励:现在你也可以在路线中使用正则表达式,例如

 [Route("api/utilities/{vendorId:int}/{utilityType:regex(^(?i)(Gas)|(Electric)$)}/{accountType:regex(^(?i)(Residential)|(Business)$)}")] public IHttpActionResult GetUtilityList(int vendorId, string utilityType, string accountType) {