C# 在一个Web API控制器中具有不同参数的两个HTTP Post方法
我试图在一个控制器中实现一个具有多个POST方法的控制器。我有以下资料:C# 在一个Web API控制器中具有不同参数的两个HTTP Post方法,c#,asp.net,rest,asp.net-web-api,C#,Asp.net,Rest,Asp.net Web Api,我试图在一个控制器中实现一个具有多个POST方法的控制器。我有以下资料: public class PatientController : ApiController { [HttpGet] public IEnumerable<Patient> All() { ... } [HttpGet] public Patient ByIndex(int index) { ... } [HttpPost] public HttpRespon
public class PatientController : ApiController
{
[HttpGet]
public IEnumerable<Patient> All() { ... }
[HttpGet]
public Patient ByIndex(int index) { ... }
[HttpPost]
public HttpResponseMessage Add([FromBody]Patient patient) { ... }
}
一切正常:)
现在,我想补充以下行动:
[HttpPost, ActionName("save")]
public void Save(int not_used = -1) { ... }
在没有向路由添加任何内容的情况下,我在Fiddler中发现了以下错误:发现了多个与请求匹配的操作
如果我将此添加到我的路由中(作为第二个或第一个,无所谓):
我会把同样的错误告诉费德勒
这可能吗?我可以在一个控制器中有多个具有不同(类型)参数的帖子吗?您的问题是您有两种方法:
保存
和添加
,并且两者都匹配您的路线API_1
。如果url稍有不同,那么您有另一条路径API_2
可以匹配,这一事实无关紧要:此路径有两种匹配方法
您有几个选择:
Save
与默认路由不匹配。特别是,您在Save中包含了一个可选参数,这意味着可以忽略它。如果参数是非可选的,它将与路由不匹配如果不更好地理解您的具体场景,我就不能说什么是最好的;不过就我个人而言,我会避免让所有这些参数和同时路由在多个操作上工作的麻烦——要么始终明确操作,要么在代码中处理任何可能的消息(即选项3或4).面对可选参数的复杂路由简直是一种痛苦。看来我必须修改路由
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "API_2",
routeTemplate: "{controller}/{action}/{not_used}",
defaults: new { not_used = "-1" },
constraints: new { action = "save|reset" });
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "API_1",
routeTemplate: "{controller}/{action}/{index}",
defaults: new { action = "EMPTY", index = RouteParameter.Optional });
…并将ActionName属性添加到所有方法:
[HttpGet, ActionName("EMPTY")]
public IEnumerable<Patient> All()
[HttpGet, ActionName("EMPTY")]
public Patient ByIndex(int index)
[HttpPost, ActionName("EMPTY")]
public HttpResponseMessage Add([FromBody]Patient patient)
[HttpPost, ActionName("save")]
public void Save(int not_used = -1)
你调用的URL可能重复?另外,你真的没有在api URL中使用正常的
/api
前缀吗?是的,没有api-该项目根本不包含MVC。当使用以下POST localhost:6850/Patient/Hi对im进行搜索时,我的目标是实现路由,以便客户端可以在没有passi的情况下调用控制器正在为save->“localhost:6850/Patient/save设置参数。“save controller”是一个选项,但我希望将该功能保留在一个类中,即使它不适合REST world。关于路由,是否有方法指定它以便我的当前接口工作?
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "API_2",
routeTemplate: "{controller}/{action}/{not_used}",
defaults: new { not_used = "-1" },
constraints: new { action = "save|reset" });
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "API_1",
routeTemplate: "{controller}/{action}/{index}",
defaults: new { action = "EMPTY", index = RouteParameter.Optional });
[HttpGet, ActionName("EMPTY")]
public IEnumerable<Patient> All()
[HttpGet, ActionName("EMPTY")]
public Patient ByIndex(int index)
[HttpPost, ActionName("EMPTY")]
public HttpResponseMessage Add([FromBody]Patient patient)
[HttpPost, ActionName("save")]
public void Save(int not_used = -1)
localhost:6850/Patient/save