princeoicq

princeoicq

导航

jQuery调用WCF示例代码

Posted on 2011-10-21 13:23  princeoicq  阅读(211)  评论(0编辑  收藏  举报

jQuery调用WCF示例代码

不废话了,直奔主题吧

wcf端:

近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即:

<%@ ServiceHost Language="C#" Debug="true" Service="ajaxSample.HelloWorld" CodeBehind="HelloWorld.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

注:如果不添加Factory,则wcf将无法用类似http://localhost/helloWorld.svc/Hello/person/name 的restful方式直接访问。

同时还要去掉web.config中的<enableWebScript />即类似:

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ajaxSample.HelloWorldAspNetAjaxBehavior">
          <!--<enableWebScript />-->
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="ajaxSample.HelloWorld">
        <endpoint address="" behaviorConfiguration="ajaxSample.HelloWorldAspNetAjaxBehavior"
          binding="webHttpBinding" contract="ajaxSample.HelloWorld" />
      </service>
    </services>
  </system.serviceModel>

好了,开始写代码,鉴于wcf调用时有GET/POST二种方式,下面把几种常用的情况都写一个示例方法:

001 using System.Collections.Generic;
002 using System.ServiceModel;
003 using System.ServiceModel.Activation;
004 using System.ServiceModel.Web;
005   
006 namespace ajaxSample
007 {
008     [ServiceContract(Namespace = "http://yjmyzz.cnblogs.com/")]
009     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
010     public class HelloWorld
011     {
012           
013         /// <summary>
014         /// 只能Post的Restful方法
015         /// </summary>
016         /// <param name="person"></param>
017         /// <param name="welcome"></param>
018         /// <returns></returns>
019         [OperationContract]
020         [WebInvoke(Method = "POST", UriTemplate = "PostRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
021         public List<string> PostRestfulTest(string person,string welcome)
022         {
023             List<string> result = new List<string>();
024   
025             result.Add("PostRestfulTest -> from server:");
026             result.Add(person);
027             result.Add(welcome);
028             return result;
029         }
030   
031         /// <summary>
032         /// 只能Get的Restful方法
033         /// </summary>
034         /// <param name="person"></param>
035         /// <param name="welcome"></param>
036         /// <returns></returns>
037         [OperationContract]
038         [WebInvoke(Method = "GET", UriTemplate = "GETRestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
039         public List<string> GETRestfulTest(string person, string welcome)
040         {
041             List<string> result = new List<string>();
042   
043             result.Add("GETRestfulTest -> from server:");
044             result.Add(person);
045             result.Add(welcome);
046             return result;
047         }
048   
049         /// <summary>
050         /// 即可Get与Post的Restful方法
051         /// </summary>
052         /// <param name="person"></param>
053         /// <param name="welcome"></param>
054         /// <returns></returns>
055         [OperationContract]
056         [WebInvoke(Method = "*", UriTemplate = "RestfulTest/{person}/{welcome}", ResponseFormat = WebMessageFormat.Json)]
057         public List<string> RestfulTest(string person, string welcome)
058         {
059             List<string> result = new List<string>();
060   
061             result.Add("RestfulTest -> from server:");
062             result.Add(person);
063             result.Add(welcome);
064             return result;
065         }
066   
067   
068         /// <summary>
069         /// 只能Post的常规方法(注:Post方式,BodyStyle必须设置成WrappedRequest或Wrapped)
070         /// </summary>
071         /// <param name="person"></param>
072         /// <param name="welcome"></param>
073         /// <returns></returns>
074         [OperationContract]
075         [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)]
076         public List<string> PostTest(string person, string welcome)
077         {
078             List<string> result = new List<string>();
079   
080             result.Add("PostRestfulTest -> from server:");
081             result.Add(person);
082             result.Add(welcome);
083             return result;
084         }
085   
086         /// <summary>
087         /// 只能Get的常规方法
088         /// </summary>
089         /// <param name="person"></param>
090         /// <param name="welcome"></param>
091         /// <returns></returns>
092         [OperationContract]
093         [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
094         public List<string> GETTest(string person, string welcome)
095         {
096             List<string> result = new List<string>();
097   
098             result.Add("GETTest -> from server:");
099             result.Add(person);
100             result.Add(welcome);
101             return result;
102         }
103   
104           
105   
106           
107     }
108 }

  

jQuery调用代码:

01 <script type="text/javascript">
02     $().ready(function () {
03  
04  
05         $.post("HelloWorld.svc/PostRestfulTest/111/222", function (data) {
06             alert("PostRestfulTest调用成功,返回值为:" + data);
07         })
08  
09         $.get("HelloWorld.svc/GETRestfulTest/333/444", function (data) {
10             alert("GETRestfulTest调用成功,返回值为:" + data);
11         })
12  
13         $.get("HelloWorld.svc/RestfulTest/555/666", function (data) {
14             alert("RestfulTest GET方式调用成功,返回值为:" + data);
15         })
16  
17  
18         $.post("HelloWorld.svc/RestfulTest/777/888", function (data) {
19             alert("RestfulTest POST方式调用成功,返回值为:" + data);
20         })
21  
22  
23         $.get("HelloWorld.svc/GETTest", { person: "aaa", welcome: "bbb" }, function (data) {
24             alert("GETTest 调用成功,返回值为:" + data);
25         });
26  
27  
28         $.ajax({
29             url: "HelloWorld.svc/PostTest",
30             type: "POST",
31             contentType: "application/json",
32             data: '{"person":"ccc","welcome":"ddd"}',
33             dataType: "html",
34             success: function (data) { alert("PostTest调用成功,返回值为:" + data); }
35         });
36     })
37 </script>