【问题标题】:How to call WebMethod?如何调用WebMethod?
【发布时间】:2012-04-08 21:17:18
【问题描述】:

我正在尝试从 JavaScript 调用 WebMethod。到目前为止,我有:

EMSWebService.asmx:

namespace EMSApplication.Web.WebServices
{
    /// <summary>
    /// Holds the Webservice methods of EMSApplication
    </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]     
    [System.Web.Script.Services.ScriptService]
    public class EMSWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

在 aspx 页面中我添加了以下内容:

<asp:ScriptManager ID="ScriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebServices/EMSWebService.asmx" />
    </Services>
</asp:ScriptManager>
<input onclick="callWebMethod();" id="btn" type="button" value="Click Me" />

JavaScript 是:

<script type="text/javascript">
    function callWebMethod() {
        EMSApplication.Web.WebServices.EMSWebService.HelloWorld(OnComplete, OnError);            
    }

    function OnComplete(result) {
        alert(result);
    }

    function OnError(result) {
        alert(result.get_message());
    }

</script>

但是方法没有执行。我收到以下 JavaScript 错误:

EMSApplication 未定义。

我有什么遗漏吗?我需要做一些其他的配置吗?

项目结构如下图所示:

JavaScript 和组件在 Login.aspx 中。

[WebService(Namespace = "http://tempuri.org/")] 的网址有什么意义


编辑:

我也尝试过使用 jQuery 并将 aspx 页面修改为:

$(document).ready(function () {
        $("#btn").click(function () {                
            $.ajax({
                type: "POST",
                url: "../WebServices/EMSWebService.asmx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);                        
                },
                failure: function (msg) {                        
                    alert(msg.d);
                }
            });
            return true;
        });
    });

我在WebMethod 中写了System.Diagnostics.Debug.WriteLine("Hello World");,它正在执行,即它正在Visual Studio 的输出窗口中打印“Hello World”,但我没有收到任何警报消息。

【问题讨论】:

  • 在客户端设置断点,例如在 Google Chrome 优秀的开发人员工具中查看 ajax 调用之前/之后发生的情况。
  • 你能验证一下scripthandlerfactory是在web.config中定义的吗?
  • 不,我没有在 web.config 中定义任何 scripthandlerfactory。我该怎么办?
  • 阅读此处msdn.microsoft.com/en-us/library/bb398998.aspx 此页面介绍了从脚本调用 Web 服务所需的操作。
  • @JeremyHoward 你能发表你的答案吗?这样我才能接受。在&lt;system.web/&gt;&lt;httpHandlers/&gt;中使用&lt;add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/&gt;后解决。非常感谢。

标签: c# javascript exception-handling asmx


【解决方案1】:

我想直接回答这个问题。

我有一个WebMethod,位于SomePage.aspx 文件中:

[WebMethod]
public static String DoSomething(String shiftName)
{
    return shiftName+" hi there";
}

问题是:我如何调用这个网络方法?因为这是 HTTP,所以答案是 HTTP POST 到服务器:

POST http://localhost:53638/SomePage.aspx/DoSomething HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: qps-ploc,en-US;q=0.5
Accept-Encoding: gzip, deflate
Host: localhost:53638
Connection: Keep-Alive
Content-Length: 23
Content-Type: application/json;charset=utf-8

{'shiftName':'contoso'}

关键需要注意的重要事项是:

  • HTTP 方法:POST GET 不起作用)
  • 您将 aspx 页面上的方法名称指定为 SomePage.aspx/[MethodName]。在这种情况下:

    SomePage.aspx/DoSomething

  • 您将方法的参数作为 JSON 传递。该方法有一个字符串参数:shiftName。这意味着我构建了 JSON:

    {'shiftName':'contoso'}
    
  • 对于请求的 JSON 内容类型,您必须指定 Content-Type 请求标头:

    ContentType: application/json;charset=utf-8
    

鉴于我的示例 WebMethod 只是获取提供的文本,附加 hi there,并返回该字符串,来自网络服务器的响应是:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 24
Connection: Close

{"d":"contoso hi there"}

HTTP 响应正文也是一个 JSON 字符串,具有一个名为 d 的属性。我不知道他们从哪里得到d,但确实是这样。

这就是您使用 http 调用 WebMethod 的方式(例如,汇编语言、COM、C#、Java、Delphi)。

最常见的问题是如何从客户端调用它使用 jQuery。

$.ajax({
       type: "POST",
       url: 'Catalogo.aspx/checaItem',
       data: "{ id : 'teste' }",
       contentType: 'application/json; charset=utf-8',
       success: function (data) {
           alert(data);
       }
});

注意:任何发布到公共领域的代码。无需署名。

【讨论】:

    【解决方案2】:

    您需要确保在您的 web.config 中定义了 scripthandlerfactory...更多 http://msdn.microsoft.com/en-us/library/bb398998.aspx

    【讨论】:

    • 谢谢。你能告诉我 [WebService(Namespace = "tempuri.org/")]
    • Tapas,你的服务的命名空间是为你的服务的消费者提供一个唯一的服务位置。这是为了防止服务在具有相同服务名称时发生冲突。在投入生产之前,您需要将命名空间更改为更独特的名称。更多关于这里的主题...social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2011-11-07
    • 2023-03-12
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多