I have a Web API service call that updates a user's preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object's properties are always null (or default values), rather than what is passed in. If I call the same exact method using a REST client (I use Postman), it works beautifully. I cannot figure out what I'm doing wrong with this but am hoping someone has seen this before. It's fairly straightforward...
Here's my request object:
public class PreferenceRequest { [Required] public int UserId; public bool usePopups; public bool useTheme; public int recentCount; public string[] detailsSections; }
Here's my controller method in the UserController class:
public HttpResponseMessage Post([FromBody]PreferenceRequest request) { if (request.systemsUserId > 0) { TheRepository.UpdateUserPreferences(request.UserId, request.usePopups, request.useTheme, request.recentCount, request.detailsSections); return Request.CreateResponse(HttpStatusCode.OK, "Preferences Updated"); } else { return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "You must provide User ID"); } }
Here's my ajax call:
var request = { UserId: userId, usePopups: usePopups, useTheme: useTheme, recentCount: recentCount, detailsSections: details }; $.ajax({ type: "POST", data: request, url: "http://localhost:1111/service/User", success: function (data) { return callback(data); }, error: function (error, statusText) { return callback(error); } });
I've tried setting the dataType & contentType to several different things ('json', 'application/json', etc) but the properties of the request object are always defaulted or null. So, for example, if I pass in this object:
var request = { UserId: 58576, usePopups: false, useTheme: true, recentCount: 10, detailsSections: ['addresses', 'aliases', 'arrests', 'events', 'classifications', 'custody', 'identifiers', 'phone', 'remarks', 'watches'] }
I can see a fully populated request object with the valid values as listed above. But in the Web API controller, the request is there, but the properties are as follows:
UserId: 0, usePopups: false, useTheme: false, recentCount: 0, detailsSections: null
FYI - I'm not doing ANY ASP.Net MVC or ASP.NET pages with this project, just using the Web API as a service and making all calls using jQuery $.ajax.
Any idea what I'm doing wrong here? Thanks!
UPDATE: I just want to note that I have many methods in this same Web API project in other controllers that do this exact same thing, and I am calling the exact same way, and they work flawlessly! I have spent the morning comparing the various calls, and there doesn't appear to be any difference in the method or the headers, and yet it just doesn't work on this particular method.
I've also tried switching to a Put method, but I get the exact same results - the request object comes in, but is not populated with the correct values. What's so frustrating is that I have about 20 controller classes in this project, and the Posts work in all of those...
This seems to be a common issue in regards to Asp.Net WebAPI.
Generally the cause of null objects is the deserialization of the json object into the C# object. Unfortunately, it is very difficult to debug - and hence find where your issue is.
I prefer just to send the full json as an object, and then deserialize manually. At least this way you get real errors instead of nulls.
If you change your method signature to accept an object, then use JsonConvert:
public HttpResponseMessage Post(Object model) { var jsonString = model.ToString(); PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString); }
Maybe it will help, I was having the same problem.
Everything was working well, and suddently, every properties was defaulted.
After some quick test, I found that it was the [Serializable] that was causing the problem :
public IHttpActionResult Post(MyComplexClass myTaskObject) { //MyTaskObject is not null, but every member are (the constructor get called). }
and here was a snippet of my class :
[Serializable] <-- have to remove that [if it was added for any reason..] public class MyComplexClass() { public MyComplexClass () { ..initiate my variables.. } public string blabla {get;set;} public int intTest {get;set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With