I would like to understand a little better about WebApi in Net and how is the correct way to called it with ajax. Little of info about my development environment: I am using .net 4.0 and visual studio 2010 and Jquery.
Model:
public class TestForm
{
public string FirstName { get; set; }
}
WebApi:
public class TestpController : ApiController
{
[HttpPost]
public HttpResponseMessage Post(TestForm form)
{
string jose = "jose";
return Request.CreateResponse(HttpStatusCode.OK, "yay");
}
}
Client side:
V1 (doesnt work, return error 405 ):
$.ajax({
url: "http://xxx/api/Testp",
type: "POST",
data: JSON.stringify({ FirstName: "Jose" }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("success");
},
error: function (xhr, errorType, exception) {
console.log("error");
}
});
V2 (works):
$.ajax({
url: "http://xxx/api/Testp",
type: "POST",
data: { FirstName: "Jose" },
dataType: 'json',
success: function(data) {
console.log("success");
},
error: function (xhr, errorType, exception) {
console.log("error");
}
});
Why do I get an error when I add contentType: "application/json; charset=utf-8"
and change the data to JSON.stringify({ FirstName: "Jose" })
, but it works when I removed the content type and send a object in data option.