C# 多参数webapi路由
我正在尝试解决如何为以下Web API控制器执行路由:C# 多参数webapi路由,c#,asp.net-web-api,asp.net-web-api-routing,C#,Asp.net Web Api,Asp.net Web Api Routing,我正在尝试解决如何为以下Web API控制器执行路由: public class MyController : ApiController { // POST api/MyController/GetAllRows/userName/tableName [HttpPost] public List<MyRows> GetAllRows(string userName, string tableName) { ... }
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格式或路由完全错误?路由对我来说似乎是一个黑魔法…问题是你的
api/MyController/GetRowsOfType/userName/tableName/rowType
URL将始终匹配第一条路由,因此永远不会到达第二条
简单修复,首先注册您的
RowsByType
路线 我看到WebApiConfig变得“失控”,其中放置了数百条路径
相反,我个人更喜欢
你让它与POST和GET混淆了
[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
(路线lead
不需要匹配方法名称GetLead
,但您希望在路线参数和方法参数上保持相同的名称,即使您可以更改顺序,例如,即使路线相反,也将recordLocator放在vendorNumber之前-我不这样做,因为为什么要让它看起来更混乱)
奖金:
现在,您也可以在routes中始终使用regex,例如
[Route("api/utilities/{vendorId:int}/{utilityType:regex(^(?i)(Gas)|(Electric)$)}/{accountType:regex(^(?i)(Residential)|(Business)$)}")]
public IHttpActionResult GetUtilityList(int vendorId, string utilityType, string accountType)
{
如何指定非可选的参数?我希望第一个参数是必需的,第二个参数是可选的。在webapiconfig中执行路由更痛苦,请参阅我关于属性路由的回答。我认为
属性路由
也是更好的选择。+1这需要API 2,但它并不总是一个选项。这是相同的建议e对于asp.net核心是正确的(没有尝试regex),但是如果我做了[Route(“~the/things/{thingId}/subthing{id}/save”)]和[Route(~the/things/{thingId}/subthing{id}/submit”)],属性routing对我有效/
[Route("GetAllRows/{user}/{table}")]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
[HttpPost]
[Route("api/lead/{vendorNumber}/{recordLocator}")]
public IHttpActionResult GetLead(string vendorNumber, string recordLocator)
{ .... }
[Route("api/utilities/{vendorId:int}/{utilityType:regex(^(?i)(Gas)|(Electric)$)}/{accountType:regex(^(?i)(Residential)|(Business)$)}")]
public IHttpActionResult GetUtilityList(int vendorId, string utilityType, string accountType)
{