ASP.NET Web API - 一个控制器上的多个POST方法?

Isa*_*aac 9 asp.net-mvc-4 asp.net-web-api

我一直在尝试向默认的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) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我添加第二个post方法时,每次发出POST请求时,都会收到错误:

"No action was found on the controller 'values' that matches the request."
Run Code Online (Sandbox Code Playgroud)

如果我注释掉其中一个方法(无论哪个方法),POST将与另一个方法一起使用.我已经尝试重命名方法,甚至[HttpPost]在两者上使用,但没有任何效果.

如何在单个ApiController中拥有多个POST方法?

编辑

这是我使用的唯一路线:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}",
    defaults: new { controller = "values", id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

Ale*_*ler 7

您必须在路线中包含该操作:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

  • 如果您从第一个POST中删除值param,它将无法明确指定操作,但您将无法发布任何数据.您只能使用唯一URI来处理帖子. (2认同)