I want to submit a form post via AJAX to my API. I have already set up my WebApiConfig.cs class as follows to enable multiple GETs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
Here is the controller action:
[HttpPost]
[ActionName("ChangeStuff")]
public string ChangeStuff(int val1, int val2, int val3)
{
//Code
}
And this is where I make the request:
var url = window.location.protocol + "//" + window.location.host + "/api" + "@Url.Action("ChangeStuff", "ApiControllerName")";
$.ajax({
url: url,
type: "POST", //Works with GET
data: { val1: val1, val2: val2, val3: val3 },
contentType: "application/json:; charset=utf-8",
dataType: "json",
success: function (msg) {
},
failure: function (msg) {
}
});
However, I get this error back when making the post:
POST http://localhost:50627/api/ApiControllerName/ChangeStuff 404 (Not Found)
I am thinking this is because of an issue with my API routing defaulting to GET requests and then failing to accept POST types (even though it is made explicit in the AJAX call). It works just fine when making GET requests.
EDIT: Neither of the following attempts worked:
data: JSON.stringify( { currentobject } )
data: { data: { currentobject } }
Is it assured that the issue is not with the modified API routes?