我一直在尝试向默认的 ValuesController 类添加第二个 POST 方法,该方法将采用 id 参数,其行为与 PUT 方法相同,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
namespace WebCalendar.Controllers {
public class ValuesController : ApiController {
// GET /values
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
// GET /values/5
public string Get(int id) {
return "value";
}
// POST /values
public void Post(string value) {
}
// POST /values/5
public void Post(int id, string value) {
Put(id, value);
}
// PUT /values/5
public void Put(int id, string value){
}
// DELETE /values/5
public void Delete(int id) {
}
}
}
问题是,当我添加第二个 post 方法时,每当我发出 POST 请求时,都会收到错误:
"No action was found on the controller 'values' that matches the request."
如果我注释掉其中一种方法(无论是哪一种),POST 将与另一种方法一起使用。我尝试过重命名这些方法,甚至对它们都使用 [HttpPost]
,但没有任何效果。
如何在一个 ApiController 中拥有多个 POST 方法?
编辑
这是我正在使用的唯一路线:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { controller = "values", id = RouteParameter.Optional }
);
最佳答案
您必须在 route 包含该操作:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
关于asp.net-mvc-4 - ASP.NET Web API - 一个 Controller 上有多个 POST 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038881/