天天看点

javascript调用WCF服务

在 ASP.NET AJAX 框架中,如果需要用 javascript 调用 WebService 或者调用 PageMethod 都是很容易实现的,主要是通过ScriptManager服务器控件协调脚本资源,生成客户端代理,实现对服务器端的访问,当然不使用ScriptManager控件,而直接用javascript或者js框架jQuery也是很容易来调用WebService的,那么javascript可以对wcf服务进行调用吗?答案是肯定的!接下来我们就演示js与wcf是如何进行通讯的。

第一步:建立一个web项目

然后在这个项目中建立一个.svc 的WCF服务框架。

vs自动生成三个文件:Service1.svc、Service1.svc.cs 、IService1.cs,且Web.config中也被自动添加了

<system.serviceModel /> 节点。

为了能在wcf服务中启用ajax,我们必须对Web.config中生成的wcf节点部分做一点修改,修改后的节点内容如下:

 <system.serviceModel>

    <behaviors>

      <endpointBehaviors>

        <behavior name="test_js_wcf.Service1Behavior">

          <enableWebScript />

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

    <services>

      <service name="test_js_wcf.Service1">

        <endpoint behaviorConfiguration="test_js_wcf.Service1Behavior" address="" binding="webHttpBinding"

               contract="test_js_wcf.IService1">

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

      </service>

    </services>

  </system.serviceModel>

第二步:构建wcf服务

IService1.cs 文件代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace test_js_wcf

{

    [ServiceContract(Namespace = "Valsun", Name = "Service1")]

    public interface IService1

    {

        [OperationContract]

         Dictionary<string,string> GetTestList(string id);

    }

}

Service1.svc 文件代码:

<%@ ServiceHost Language="C#" Debug="true" Service="test_js_wcf.Service1" CodeBehind="Service1.svc.cs" %>

Service1.svc.cs 文件代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Activation;

namespace test_js_wcf

{

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class Service1 : IService1

    {

        public Dictionary<string, string> GetTestList(string id)

        {

            // 定义一个字典对象

            Dictionary<string, string> dic = new Dictionary<string, string>();

            // 方便测试,直接构造一些数据来模拟数据库中的数据

            dic.Add("1" + id, "上海");

            dic.Add("2" + id, "北京");

            dic.Add("3" + id, "广州");

            dic.Add("4" + id, "深圳");

            dic.Add("5" + id, "南京");

            // 返回值

            return dic;

        }

    }

}

第三步:建立一个.aspx 页面来调用wcf服务

<body>

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">

        <Services>

            <asp:ServiceReference Path="~/Service1.svc" />

        </Services>

    </asp:ScriptManager>

    <div>

        <asp:DropDownList ID="ddl" runat="server" Width="200">

            <asp:ListItem Text="1" Value="1"></asp:ListItem>

            <asp:ListItem Text="2" Value="2"></asp:ListItem>

            <asp:ListItem Text="3" Value="3"></asp:ListItem>

        </asp:DropDownList>

        <br />

        <br />

        <input id="btnQueryDictionary" type="button" value="测试" οnclick="btnQuery();" />

        <br />

        <br />

        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>

    </div>

    </form>

</body>

<script language="javascript" type="text/javascript">

    function btnQuery() {

        var ddl = $get('<%=ddl.ClientID %>');

        var id = ddl.options[ddl.selectedIndex].value;

        var wcfProxy = new Valsun.Service1();

        wcfProxy.GetTestList(id, OnSucceededCallback, OnFailedCallback);

    }

    function OnSucceededCallback(result, userContext, methodName) {

        if (methodName == "GetTestList") {

            var msg = "";

            // 注意这里的访问方式!!!

            for (var key in result) {

                msg += result[key].Key + " : " + result[key].Value + "/n";

            }

            $get('<%=lblMsg.ClientID%>').innerText = msg;

        }

    }

    function OnFailedCallback(error, userContext, methodName) {

        alert("异常信息:" + error.get_message() + "/n" +

              "异常类型:" + error.get_exceptionType() + "/n" +

              "堆栈信息:" + error.get_stackTrace());

    }

</script>

测试通过!代码不用多解释,看看大概就知道意思了,这只是一个入门示例,更深入的应用稍后讲解。

继续阅读