0

所以我有一些问题。问题的目标是,当我尝试使用 Ajax 从用户控件调用 Web 服务时,出现 500 内部服务器错误。

有我的代码示例:

网络服务.CS

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class BudgetJson : System.Web.Services.WebService {

    public BudgetJson () 
    {
    }



    [WebMethod]
    public static String GetRecordJson()
    {
        return " Hello Master, I'm Json Data ";
    }
}

用户控制 (.Ascx) 文件(Ajax 调用)

$(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "BudgetJson.asmx",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) 
                {
                    alert(msg);
                }
            });
        });

因此,当页面加载并发送请求时,我得到了这样的响应:

肥皂:ReceiverSystem.Web.Services.Protocols.SoapException:服务器无法处理请求。---> System.Xml.XmlException:根级别的数据无效。第 1 行,位置 1。位于 System.Xml.XmlTextReaderImpl.Throw(String res, String arg) 处 System.Xml.XmlTextReaderImpl.Throw(Exception e) 处 System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() 处 System.Xml.XmlTextReaderImpl。 ParseDocumentContent() 在 System.Xml.XmlTextReaderImpl.Read() 在 System.Xml.XmlTextReader.Read() 在 System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read() 在 System.Xml.XmlReader.MoveToContent() 在System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement() 处 System.Web.Services.Protocols 处的 System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()。

如果我将方法名称添加到 url,我会收到这样的错误:

未知的 Web 方法 GetRecordJson。参数名称:methodName 说明:当前web请求执行过程中发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.ArgumentException:未知的 Web 方法 GetRecordJson。参数名称:methodName

任何解决方案?

4

1 回答 1

2

服务器端的几件事:

该方法不应该是静态的。这只是 ASPX 页面上的“页面方法”的情况。

其次,您需要使用[ScriptService]属性来装饰服务类,以便能够在 JSON 中与之通信,我假设您可能想要这样做,因为您使用的是 jQuery。

[ScriptService]
public class BudgetJson : System.Web.Services.WebService {
  [WebMethod]
  public String GetRecordJson()
  {
    return " Hello Master, I'm Json Data ";
  }
}

在客户端,您需要指定要在$.ajax()URL 中执行的方法:

$.ajax({
  type: "POST",
  url: "BudgetJson.asmx/GetRecordJson",
  data: "{}",
  // The charset and dataType aren't necessary.
  contentType: "application/json",
  success: function (msg) {
    alert(msg);
  }
});

您还可以稍微简化一下$.ajax()用法,如上所示。字符集不是必需的,jQuery 会自动从服务器发回的标头中检测数据类型。

于 2011-12-13T17:56:53.207 回答