500错误 - JSON对象POST到.ASMX webservice

时间:2011-12-05 17:02:16

标签: jquery ajax json web-services asmx

这里的问题简短而甜蜜。当我尝试将JSON对象传递给ASMX Web服务时,我收到500错误。请注意,如果我 将params声明为单个变量 (例如。int ID, int OrderHeaderID等) 我没有收到错误 即可。我不明白为什么会出现这个问题,我之前已成功地以这种方式传递对象,可能使用不同的语法,但我不记得了。

JS:

var returnHeader = {
    ID: -1,
    OrderHeaderID: parseInt(getQueryStringKey('OrderID')),
    StatusID: 1,
    DeliveryCharge: 0,
    CreatedBy: $('span[id$="lblHidUsername"]').text(),
    ApprovedBy: $('span[id$="lblHidUsername"]').text()
};

$.ajax({
    type: "POST",
    url: 'Order.asmx/SaveReturnHeader',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(returnHeader),
    success: function (result) {
        if (result.Status == 'OK') {
            GetReturns();
        }
        else {
            $('#divMessage').show().html(result.Data.Message).addClass('error');
        }
    },
    error: function (x, e) {
        if (x.status == 500) {
            $('#divMessage').show().html('An unexpected server error has occurred, please contact support').addClass('error');
        }
    }
});

服务器:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object SaveReturnHeader(BEReturnHeader returnHeader)
{
    try
    {
        return new
        {
            Status = "OK",
            Data = ""
        };                
    }
    catch (Exception ex)
    {
        return new
        {
            Status = "ERROR",
            Data = ex
        }; 
    }
}

对象(简称为简称):

public int ID ...
public int OrderHeaderID ...
public int StatusID ...
public decimal DeliveryCharge ...
public string CreatedBy  ...
public string ApprovedBy ...

请求数据:

{"ID":-1,"OrderHeaderID":5,"StatusID":1,"DeliveryCharge":0,"CreatedBy":"77777777","ApprovedBy":"77777777"}

响应标题:

HTTP/1.1 500 Internal Server Error
Date: Mon, 05 Dec 2011 16:38:36 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
jsonerror: true
Cache-Control: private
Content-Type: application/json
Content-Length: 91

响应数据:

{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}

FIX:

必须包装JSON对象,以便在服务器上识别它:

var params = {
            returnHeader: {
                ...
            }
        };

...
data: JSON.stringify(params),
...

{"returnHeader":{"ID":-1,"OrderHeaderID":5,"StatusID":1,"DeliveryCharge":0,"CreatedBy":"77777777","ApprovedBy":"77777777"}}

1 个答案:

答案 0 :(得分:5)

您只传入对象的属性,而不是整个对象容器。所以,web方法正在期待这样的事情:

{returnHeader:{"ID":-1,"OrderHeaderID":5,"StatusID":1,"DeliveryCharge":0,"CreatedBy":"77777777","ApprovedBy":"77777777"}}