Calling Web Api POST always receives null value from jQuery

大兔子大兔子 提交于 2021-02-07 13:24:33

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/14490149/calling-web-api-post-always-receives-null-value-from-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!