我正在尝试找出如何为以下 Web API Controller 进行路由:
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 变得“失控”,其中放置了数百条路由。
相反,我个人更喜欢 Attribute Routing
您正在使它与 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 中的任何内容,因此它会找到您的METHOD 与 GetAllRows,但方法本身,该名称可以是您想要的任何名称,因此只要调用者与 ROUTE 中的 URL 匹配,如果您真的愿意,您可以为该方法放入 GetMyStuff。
更新:
我实际上更喜欢显式
HTTP方法
而且我更喜欢将路由参数与方法参数相匹配
[HttpPost]
[Route("api/lead/{vendorNumber}/{recordLocator}")]
public IHttpActionResult GetLead(string vendorNumber, string recordLocator)
{ .... }
(路由 lead
不需要与方法名称 GetLead
匹配,但您需要在路由参数和方法参数上保持相同的名称,即使您可以更改顺序,例如将 recordLocator 放在 vendorNumber 之前,即使路线是相反的 - 我不这样做,因为为什么看起来更困惑)。
奖励: 现在您也可以随时在路由中使用 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)
{
关于c# - 具有多个参数的 Web API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140305/