I’m struggling with the “new” WebApi in Asp.Net…
I just want to post some Json but it is not deserializing my data… what am i doing wrong?!
Controller class
public class UtilityController : ApiController
{
[HttpPost]
public string Bla(Bla bla)
{
return "bla";
}
}
Bla Class:
public class Bla
{
public string Een { get; set; }
public string Twee { get; set; }
}
Api config:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Posted Data:
var bla = $.parseJSON('{"Een":"UNO","Twee":"DUE"}');
$.ajax({
type: "POST",
url: "/api/utility/Bla",
data: {Bla : bla},
dataType: "json"
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
You are not sending a JSON request. You are sending an
application/x-www-form-urlencodedrequest.So make sure that you are sending a real JSON request:
Notice how I have set the correct
contentTypeheader toapplication/json, how I’ve used theJSON.stringifymethod to send a real JSON request and how I’ve gotten rid of the uselessdataType: 'json'parameter which jQuery is perfectly capable of automatically deducing from the Content-Type response header that the server sends.