In a project I completed several months I had this in the controller:
public HttpResponseMessage Post(PersonModel model)
{
}
I could send the ajax post with the members inside a json object, and WebAPI would seamlessly populate each property within the model.
However, I’ve just started a new project and am doing the same but the model inside the controller is now just null. The binding appears to be broken. Has something changed on ASP.NET WebAPI that prevents this from happening?
This is my ajax request:
$.ajax({ url: "api/auth", type: "post", data: { username: "jon", password: "123" },dataType: "json", contentType: "application/json; charset=utf-8" });
Your ajax request content body has the format of
application/x-www-form-urlencoded:username=jon&password=123, but you have set content-type toapplication/json. Because of this, Json.NET serializer failed to deserialize the request body content.You could do one of the following:
Change the content-type to be
application/x-www-form-urlencodedinstead of explicitly setting the contentType to beapplication/jsonContinue to use
application/jsonbut Json stringify your data:data: JSON.stringify({ username: "jon", password: "123" })Hope this helps.