Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API - Multiple POST methods on one controller?

I've been trying to add a second POST method to the default ValuesController class that will take an id parameter and act identical to the PUT method, like so:

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) {
        }
    }
}

Problem is, when I add this second post method, any time I make a POST request, I get the error:

"No action was found on the controller 'values' that matches the request."

If I comment out one of the methods (doesn't matter which one), POST will work with the other method. I've tried renaming the methods, and even using [HttpPost] on both of them, but nothing has worked.

How can I have more than one POST method in a single ApiController?

EDIT

Here is the only route that I'm using:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}",
    defaults: new { controller = "values", id = RouteParameter.Optional }
);
like image 640
Isaac Avatar asked Apr 06 '12 03:04

Isaac


People also ask

Can we have multiple post method in Web API?

Open your controller class, in our project its ValuesController. cs >> Copy paste below code, these are two sample post methods with a string input and return parameter – you can write your business logic in it. Similarly, you can add any number of POST, GET, PUT, DELETE methods in one controller.

Can a controller have multiple get methods?

Usually a Web API controller has maximum of five actions - Get(), Get(id), Post(), Put(), and Delete(). However, if required you can have additional actions in the Web API controller.


1 Answers

You have to include the action in your route:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
like image 111
Alexander Zeitler Avatar answered Sep 17 '22 15:09

Alexander Zeitler