jeepingviini jeepingviini - 15 days ago 7
Ajax Question

Multiple actions were found that match the request with web api

Im making a website with web api, I tried to send json to my controller but this is the error I keep getting.

Multiple actions were found that match the request:
Post on type AuctionWebsiteASP.Controllers.MovesController
readDatabase on type AuctionWebsiteASP.Controllers.MovesController
newItem on type AuctionWebsiteASP.Controllers.MovesController


First I tried searching for a fix but none of the fixes here helped.

My Controller

public class MovesController : ApiController
{
[AcceptVerbs("GET", "POST")]
public HttpResponseMessage Post([FromBody] Product product)
{
products.Add(product);
newItem();
return Request.CreateResponse(HttpStatusCode.OK, product);
}
}


My JS

$.ajax({
type: "POST",
dataType: "json",
url: "/api/moves/",
data: source,
success: function (data) {
$("#nStart").val(null);
$("#nImg").val(null);
$("#nMaker").val(null);
$("#nModel").val(null);
$("#nSerial").val(null);
$("#nCpu").val(null);
$("#nRam").val(null);
$("#nGpu").val(null);
$("#nStorage").val(null);
$("#nBattery").val(null);
$("#nDrivers").val(null);
$("#nAccessories").val(null);
$("#nNotes").val(null);
console.log("Data has been sent!");
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("ERROR!");
}
});


Thanks already!

Answer

Your route is probably like this

routes.MapHttpRoute(
  name: "API Default",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }); 

But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:

routes.MapHttpRoute(
  name: "API Default",
  routeTemplate: "api/{controller}/{action}/{id}",
  defaults: new { id = RouteParameter.Optional });

Try to use Route attribute to distinguish each action e.g

 public class MovesController : ApiController
 {
     [Route("Product")]
     public HttpResponseMessage Post([FromBody] Product product)
     {
         products.Add(product);
         newItem();
         return Request.CreateResponse(HttpStatusCode.OK, product);
     }
  }

$.ajax({ type: "POST", dataType: "json", url: "/api/moves/product", data: source, success: function (data) { $("#nStart").val(null); $("#nImg").val(null); $("#nMaker").val(null); $("#nModel").val(null); $("#nSerial").val(null); $("#nCpu").val(null); $("#nRam").val(null); $("#nGpu").val(null); $("#nStorage").val(null); $("#nBattery").val(null); $("#nDrivers").val(null); $("#nAccessories").val(null); $("#nNotes").val(null); console.log("Data has been sent!"); }, error: function (error) { jsonValue = jQuery.parseJSON(error.responseText); alert("ERROR!"); } });