调用Web Api POST始终从jQuery接收空值 [英] Calling Web Api POST always receives null value from jQuery

查看:39
本文介绍了调用Web Api POST始终从jQuery接收空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Web API,现在过得很愉快.至少使用GET.由于某些原因,当我尝试通过jQuery $.post() $.ajax()发送数据时,我的 ApiController 接收到的值始终为null.更奇怪的是,使用Fiddler向其发送数据就可以了.我确定这是我在javascript中构造对象的方式的问题,但我似乎找不到它.这是代码:

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

还有jQuery ...

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);
}

更新:因此,这显然可以在ASP.NET WebForms(.NET 3.5)中正常运行,但不能在同一项目的MVC4中运行...

UPDATE: So apparently this works fine in ASP.NET WebForms (.NET 3.5), but not in MVC4 in the same project...

推荐答案

您需要从jquery发送"= mystring" 而不是"mystring" .这是一个已知问题,这是由于Web API中映射数据的方式所致.

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.

这篇关于调用Web Api POST始终从jQuery接收空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆