正在将json发布到WebService

本文关键字:WebService json | 更新日期: 2023-09-27 18:26:18

我想将json对象传递给[WebMethod]。

我的[WebMethod]是这样的;

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void UpdateBooksOrder(Success succ)
{
    try
    {
        if (succ != null)
        {                            
            updateDal.LogSGDetails(succ);
        }
    }
    catch (Exception ex)
    {
        logger.Error("exception ", ex);
    }
}

并且,我将[WebMethod]URL作为;

http://localhost:50596/OrderStatusUpdate.asmx?op=UpdateBooksOrder

为了进行测试,我使用像这样的html+ajax将json对象传递到上面的[WebMethod];

 <script type="text/javascript">
        $("#btnUpdate").live("click", function () {
        //alert("OK");
            var succ = {};
            succ.id = "1";
            succ.refrerence = "148997";
            succ.external_ref = "GF0000148997";
            succ.status = "1";
            succ.status_name = "test";          
            $.ajax({
                type: 'POST',
                url: 'http://localhost:50596/OrderStatusUpdate.asmx?op=UpdateBooksOrder',
                data: "{succ:" + JSON.stringify(succ) + "}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function () {
                    alert("OK");
                }
            });
        });
    </script>

当我运行WebService项目并通过html调用它时,我得到以下错误;

Status Code:405 Method Not Allowed

请给我一个解决问题的方法。

正在将json发布到WebService

我用下面的方式完成了这项工作。它运行良好。Web服务

   [WebMethod]
    public string OrderstatusUpdate(OrderStatus orderStatus)
    {
       //do what ever
        return "Success";
    }

订单状态类别

[Serializable]
public class OrderStatus
{
    public int Id { get; set; }
    public string Reference { get; set; }
}

Java脚本

function resolveObject(data) {
        if (!data.hasOwnProperty('d')) return data;
        else return data.d;
    }
    $.ajaxSetup({ "contentType": "application/json;charset=utf-8", "dataType": "json", "error": function (e) { console.log(e); return; } });
    function saveOrder() {

        var a = { orderStatus: {} };
        a.orderStatus.Id = 1;
        a.orderStatus.Reference = "reference";
        $.ajax({
            type: "POST",
            url: "../services/OrderService.asmx/OrderstatusUpdate",
            data: JSON.stringify(a),
            success: function (r) {
                alert(resolveObject(r));
            }
        });
    }

并确保您已经在Web服务类之前取消了对以下行的注释

[System.Web.Script.Services.ScriptService]

[WebMethod]属性通常用于较旧的xml web服务。

这是什么类型的项目?如果这是一个较新的项目,请考虑使用像[HttpPost]这样的较新构造。你能(用fiddler)把请求贴出来进行进一步调查吗?