Web Api POST call always gets null value from jQuery

I am using ASP.NET Web API and I have a great time. At least with GET. For some reason, when I try to send data via jQuery $.post() or $.ajax() , the values ​​received by my ApiController are always zero. What's even weirder, so sending data with it using Fiddler is very good. I am sure that this is a problem with the way I create the object in javascript, but I cannot find it. Here is the code:

 // C# [HttpPost] public HttpResponseMessage BeginTrack([FromBody]string requestContext) { // requestContext is always null. Except when it comes from Fiddler. RequestContext ctx = null; if (Request.Content.Headers.ContentType.MediaType == "application/json") { try { ctx = Json.Decode<RequestContext>(requestContext); } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An error has occured while processing your request. See Exception for details.", ex); } } if (ctx == null) //... 

And jQuery ...

 getRequestContext = function (source, docType, id, ip) { return { SourceSite: source, DocumentType: docType, Id: id, HostUrl: document.URL, HostDomain: document.location.hostname, IPAddress: ip, UserAgent: navigator.userAgent, Referrer: document.referrer }; }, beginTracking = function (done, fail) { var data = JSON.stringify(getRequestContext('none', 'P', 0, 'ip')); $.post( serviceBase + "/Tracking/BeginTrack", data, done, "json" ).fail(fail); } 

UPDATE This seems to work just fine in ASP.NET WebForms (.NET 3.5), but not in MVC4 in the same project ...

+6
source share
1 answer

You need to send "=mystring" and not "mystring" from jquery. This is a known issue with how data is displayed in the web API.

+5
source

All Articles