KiL*_*iLa 5 c# asp.net rest asp.net-web-api
我正在尝试在一个控制器中实现一个带有多个POST方法的Controller.我有以下内容:
public class PatientController : ApiController
{
[HttpGet]
public IEnumerable<Patient> All() { ... }
[HttpGet]
public Patient ByIndex(int index) { ... }
[HttpPost]
public HttpResponseMessage Add([FromBody]Patient patient) { ... }
}
Run Code Online (Sandbox Code Playgroud)
我在我的路由上有这个:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
"API_1",
"{controller}/{index}",
new { index = RouteParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作:)
现在,我想添加以下操作:
[HttpPost, ActionName("save")]
public void Save(int not_used = -1) { ... }
Run Code Online (Sandbox Code Playgroud)
在没有向路由添加任何内容的情况下,我在Fiddler中收到以下错误:找到了与请求匹配的多个操作.
如果我将此添加到我的路由(作为第二个或第一个,无所谓):
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
"API_2",
"{controller}/{action}/{not_used}",
new { not_used = RouteParameter.Optional },
new { action = "save|reset" }); // Action must be either save or reset
Run Code Online (Sandbox Code Playgroud)
我得到同样的错误到Fiddler.
这甚至可能吗?我可以在一个控制器中有多个具有不同(类型)参数的POST吗?
您的问题是您有两种方法:Save
和Add
,并且都与您的路线匹配API_1
。事实上,API_2
如果 url 稍有不同,您还有另一条可能会匹配的路线,这一事实并不重要:您对此路线有两种匹配方法。
您有几个选择:
Save
默认路由不匹配。特别是,您在“保存”中包含了一个可选参数,这意味着可以省略。如果参数是非可选的,它将与路由不匹配。ServiceStack
)如果没有更好地了解您的具体情况,我真的无法说出什么是最好的;尽管就我个人而言,我会避免让所有这些参数和同时路由在多个操作上工作的棘手问题 - 要么始终明确操作,要么在代码中解决任何可能的消息(即选项 3 或 4)。面对可选参数的复杂路线简直是一种痛苦。
归档时间: |
|
查看次数: |
7620 次 |
最近记录: |