[英]Web API routing with multiple parameters
我正在尝试研究如何为以下 Web API 控制器进行路由:
public class MyController : ApiController
{
// POST api/MyController/GetAllRows/userName/tableName
[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
// POST api/MyController/GetRowsOfType/userName/tableName/rowType
[HttpPost]
public List<MyRows> 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 格式或路由完全错误? 路由对我来说似乎是黑魔法......
我已经看到WebApiConfig变得“失控”,其中放置了数百条路由。
相反,我个人更喜欢属性路由
你让它与 POST 和 GET 混淆
[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
HttpPost和GetAllRows ?
为什么不这样做:
[Route("GetAllRows/{user}/{table}")]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
或更改为 Route("PostAllRows" 和 PostRows 我认为您确实在执行 GET 请求,因此我显示的代码应该适合您。您来自客户端的调用将是 ROUTE 中的任何内容,因此它将使用 GetAllRows 找到您的方法,但是方法本身,该名称可以是您想要的任何名称,因此只要调用者与 ROUTE 中的 URL 匹配,您就可以为该方法放入 GetMyStuff(如果您真的想要的话)。
更新:
我实际上更喜欢explicit
使用HTTP 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)
{
问题是您的api/MyController/GetRowsOfType/userName/tableName/rowType
URL 将始终匹配第一个路由,因此永远不会到达第二个路由。
简单修复,首先注册您的RowsByType
路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.