I'm fairly new to MVC5 and Web API. I'm trying to consume a web API service via ajax post. I've created the service and when I'm calling it via the browser URL it works. Via ajax I'm getting Method not allowed error. I've tried a few solutions with no success. Disables WebDav. The call is from the same domain.
I've created the web API as follows:
public class ComicAPIController : ApiController
{
private List<ComicInput> ComicList = new List<ComicInput>(); //temp comic DB
public ComicAPIController()
{
ComicInput tmp = new ComicInput();
tmp.name = "Superman";
tmp.page = new List<Page>();
tmp.page.Add(new Page());
tmp.GenerateXML();
ComicList.Add(tmp);
tmp = new ComicInput();
tmp.name = "Spiderman";
tmp.GenerateXML();
ComicList.Add(tmp);
}
// GET: api/ComicAPI
public IEnumerable<ComicInput> Get()
{
return ComicList;
}
// GET: api/ComicAPI/5
public ComicInput Get(string id)
{
///will find in db
return ComicList.Find(e => e.name == id); ;
}
// POST: api/ComicAPI
public IEnumerable<ComicInput> Post(string value)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
ComicInput objComic = new ComicInput();
objComic = jsonSerializer.Deserialize<ComicInput>(value);
ComicList.Add(objComic);
return ComicList;
}
// PUT: api/ComicAPI/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ComicAPI/5
public IEnumerable<ComicInput> Delete(string id)
{
ComicList.Remove(ComicList.Find(E => E.name == id));
return ComicList;
}
}
and then created a test controller and view to consume the API.
function SendData()
{
jQuery.support.cors = true;
var myComic = {
name: "Superman Forever",
series: "Series",
author: "Stan Lee",
pages: {
image: "URL",
frames: {
topLeftX: 50,
topLeftY: 0,
width: 55,
height: 90,
rotation: {
degrees: 0,
centerX: 0,
centerY: 0
},
cropping: {
shape: "rect",
tlx: 0,
tly: 0,
w: 160,
h: 90,
color: "rgba(0,0,0,1)",
opacity: 1
},
filters: null,
transition: {
type: "move",
time: 1000
},
requireUserInput: false
}
}
};
$.ajax({
url: 'http://localhost/Web/api/ComicAPI',
type: 'POST',
data: JSON.stringify(myComic),
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
}
Try adding dataType: "json",
to the ajax call like so...
$.ajax({
url: 'http://localhost/Web/api/ComicAPI',
type: 'POST',
data: JSON.stringify(myComic),
dataType: "json", // Add this here
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});