天天看点

WCF简单教程(10) Ajax调用

第十篇:Ajax调用WCF

好久不更新了,今天写一写如何用Ajax调用WCF服务。在WebService时代,只需要加一行[System.Web.Script.Services.ScriptService]就可以使用Ajax调用了(要求.Net 3.5),到了WCF中,要稍微复杂一些。

写个小DEMO,这回是基于IIS建一个WCF工程,服务端是一个DataService.svc文件,客户端我们自己写一个Client.htm。

1、服务端

定义服务契约,没什么新鲜的,只有一个GetUser方法。(IDataService.cs)

using System; 

using System.ServiceModel; 

namespace WebServer 

    [ServiceContract] 

    public interface IDataService 

    { 

        [OperationContract] 

        User GetUser(); 

    } 

实现类也超级简单,返回一个User对象。(DataService.svc.cs)

    public class DataService : IDataService 

        public User GetUser() 

        { 

            return new User { Name = "BoyTNT", Age = 30 }; 

        } 

其中的User是数据契约,只有两个成员。(User.cs)

using System.Runtime.Serialization; 

    [DataContract] 

    public class User 

        [DataMember] 

        public string Name { get; set; } 

        public int Age { get; set; } 

然后是重点的Web.config文件了,要启用Ajax访问,需要对endpoint进行一下特殊声明(绿色注释部分)。下面只节选了system.serviceModel节点。

<system.serviceModel> 

    <behaviors> 

        <serviceBehaviors> 

            <behavior name="WebServer.DataServiceBehavior"> 

                <serviceMetadata httpGetEnabled="true" /> 

            </behavior> 

        </serviceBehaviors> 

   <!--增加一个endpoint的Behavior,命名为AjaxBehavior,为其下加一个enableWebScript节点,表示允许使用脚本访问--> 

        <endpointBehaviors> 

            <behavior name="AjaxBehavior"> 

                <enableWebScript/> 

        </endpointBehaviors> 

    </behaviors> 

    <services> 

        <service behaviorConfiguration="WebServer.DataServiceBehavior"  name="WebServer.DataService"> 

 <!--使用webHttpBinding,并且标明使用上面定义的AjaxBehavior--> 

            <endpoint address="" binding="webHttpBinding" contract="WebServer.IDataService" behaviorConfiguration="AjaxBehavior" /> 

        </service> 

    </services> 

</system.serviceModel> 

2、客户端

在工程里加一个Client.htm,注意ajax请求不能跨域,因此必须和服务端放到一块儿。我这里使用了jquery来进行ajax访问。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 

    <title>接口测试程序</title> 

    <script language="javascript" src="jquery-1.4.2.js"></script> 

    <script language="javascript"> 

     function executeAjaxQuery() { 

         $.ajax({ 

            "url": "DataService.svc/GetUser",    //注意访问的url的写法,是服务名+方法名,这点和WebService是一致的 

            "cache": false, 

            "async": true, 

            "type": "POST", 

            "dataType": "json", 

            "contentType": "application/json; charset=utf-8", 

            "data": {},     //如果有参数,在这里传递 

            success: function (json) { 

                //结果被封装到json.d属性中,数据契约中定义的两个成员都能取到 

                $("#result").val("Name=" + json.d.Name + ", Age=" + json.d.Age); 

            }, 

            error: function (x, e) { 

                $("#result").val(x.responseText); 

            } 

        }); 

     }  

    </script> 

</head> 

<body> 

<input type="button" value="获取用户" onclick="executeAjaxQuery()" /><br /> 

<textarea id="result" style="width:400px;height:200px"></textarea> 

</body> 

</html> 

OK,运行一下,在结果窗口里应该能收到“Name=BoyTNT, Age=30”。如果抓一下包,能看到服务端返回的内容是:

{"d":{"__type":"User:#WebServer","Age":30,"Name":"BoyTNT"}} 

这就是为什么要从json.d中取数据的原因。

     本文转自 BoyTNT 51CTO博客,原文链接:http://blog.51cto.com/boytnt/857350,如需转载请自行联系原作者

继续阅读