Mou*_*ark 25 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)
{
...
}
// POST api/MyController/GetRowsOfType/userName/tableName/rowType
[HttpPost]
public List<MyRows> GetRowsOfType(string userName, string tableName, string rowType)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
目前,我正在使用此路由到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
});
Run Code Online (Sandbox Code Playgroud)
但目前只有第一种方法(有2个参数)正在工作.我是在正确的路线上,还是我的URL格式或路由完全错误?路由对我来说似乎是黑魔法......
Tom*_*kel 51
我看到WebApiConfig " 失控",其中放置了数百条路线.
相反,我个人更喜欢属性路由
你正在使它与POST和GET混淆
[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
Run Code Online (Sandbox Code Playgroud)
HttpPost和GetAllRows?
为什么不这样做:
[Route("GetAllRows/{user}/{table}")]
public List<MyRows> GetAllRows(string userName, string tableName)
{
...
}
Run Code Online (Sandbox Code Playgroud)
或更改为Route("PostAllRows"和PostRows我认为你真的在做一个GET请求,所以我展示的代码应该适合你.来自客户端的调用将在ROUTE中为什么,所以它将使用GetAllRows找到你的方法,但方法本身,名称可以是你想要的任何东西,所以只要调用者匹配ROUTE中的URL,如果你真的想要,你可以为该方法输入GetMyStuff.
更新:
我实际上更喜欢explicit使用HTTP methods
AND 类型,我更喜欢将路径参数与方法参数匹配
[HttpPost]
[Route("api/lead/{vendorNumber}/{recordLocator}")]
public IHttpActionResult GetLead(string vendorNumber, string recordLocator)
{ .... }
Run Code Online (Sandbox Code Playgroud)
(路线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)
{
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 16
问题是您的api/MyController/GetRowsOfType/userName/tableName/rowTypeURL将始终与第一条路线匹配,因此永远不会达到第二条路线.
简单修复,RowsByType首先注册您的路线.
| 归档时间: |
|
| 查看次数: |
78990 次 |
| 最近记录: |