错误- JSON对象POST到.asmx web服务



问题要简洁明了。当我尝试将JSON对象传递给ASMX web服务时,我得到了500个错误。注意,如果我将参数声明为单独的变量(例如: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":""}

修复:

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

var params = {
            returnHeader: {
                ...
            }
        };
...
data: JSON.stringify(params),
...
{"returnHeader":{"ID":-1,"OrderHeaderID":5,"StatusID":1,"DeliveryCharge":0,"CreatedBy":"77777777","ApprovedBy":"77777777"}}

您只传递对象的属性,而不是整个对象容器。所以,web方法期望的是这样的东西:

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

最新更新