Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Web Api POST always receives null value from jQuery

I'm using ASP.NET Web API, and I'm having a wonderful time. At least with GETs. For some reason when I try to send data via jQuery $.post() or $.ajax(), the values received by my ApiController are always null. What's more strange is that sending data to it with Fiddler does just fine. I'm sure it's a problem with how I'm constructing the object in javascript, but I can't seem to 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 the 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: So apparently this works fine in ASP.NET WebForms (.NET 3.5), but not in MVC4 in the same project...

like image 724
Stephen Collins Avatar asked Jan 23 '13 21:01

Stephen Collins


1 Answers

You need to send "=mystring" rather than "mystring" from jquery. This is a known issue which is due to the way data are mapped in Web API.

like image 62
Aliostad Avatar answered Sep 22 '22 13:09

Aliostad