对于同一HttpVerb多个动作 [英] Multiple actions for the same HttpVerb
问题描述
我有一个Web API控制器执行以下操作:
I have a Web API controller with the following actions:
[HttpPut]
public string Put(int id, JObject data)
[HttpPut, ActionName("Lock")]
public bool Lock(int id)
[HttpPut, ActionName("Unlock")]
public bool Unlock(int id)
和以下途径映射:
routes.MapHttpRoute(
name: "Api",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "ApiAction",
routeTemplate: "api/{controller}/{action}/{id}"
);
当我提出以下要求一切正常:
When I make the following requests everything works as expected:
PUT /api/items/Lock/5
PUT /api/items/Unlock/5
但是,当我试图做一个请求:
But when I attempt to make a request to:
PUT /api/items/5
我得到了以下异常:
I get the following exception:
Multiple actions were found that match the request:
Put(int id, JObject data)
Lock(int id)
Unlock(int id)
我尝试添加一个空的动作名称为缺省路由,而是没有帮助:
I tried adding an empty action name to the default route but that did not help:
[HttpPut, ActionName("")]
public string Put(int id, JObject data)
任何想法如何,我可以用自定义动作的名称结合REST风格的默认路由?
Any ideas how I can combine default RESTful routing with custom action names?
编辑:路由机制不是由控制器的选择困惑。它是由的选择困惑的的动作的一个控制器上。我需要的是指定的任何操作时相匹配的默认操作。希望澄清的事情。
The routing mechanism is not confused by the choice of controller. It is confused by the choice of action on a single controller. What I need is to match the default action when no action is specified. Hope that clarifies things.
推荐答案
的帮助下吉斯卡尔Biamby ,我发现其中我指出了正确的方向这个答案。最后,要解决这个特定的问题,我就是这么做的:
With the help of Giscard Biamby, I found this answer which pointed me in the right direction. Eventually, to solve this specific problem, I did it this way:
routes.MapHttpRoute(
name: "ApiPut",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "Put" },
constraints: new { httpMethod = new HttpMethodConstraint("Put") }
);
由于@GiscardBiamby
Thanks @GiscardBiamby
这篇关于对于同一HttpVerb多个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!