zoukankan      html  css  js  c++  java
  • WCF REST调用

     

    REST调用

    上篇写的是Ajax调用WCF,今天写一篇如何以REST方式调用WCF服务。不知道REST是什么的同学,可以去google一下。对某些类型的应用,REST还是相当不错的方式,所以专门写一篇来说明一下开发方法。

    老规矩,上代码,直接在代码注释里讲解。


    1、服务端:

    服务契约,我们定义CRUD4个方法(增查改删),对应HTTP METHOD分别为PUT/GET/POST/DELETE:

    1. using System; 
    2. using System.ServiceModel; 
    3. using System.ServiceModel.Web;  //这个命名空间要求引入System.ServiceModel.Web.dll
    4.  
    5. namespace Server 
    6.     [ServiceContract(Namespace = "WCF.Demo")] 
    7.     public interface IData 
    8.     { 
    9.         //WebInvoke中标明REST的相关属性,以这个方法为例,调用的Url是 ..../Data/key/data,HTTP方法是PUT,响应为Json格式(也可以换成xml) 
    10.         //这样如果客户端用PUT方法访问 ..../Data/1/100,就会映射到CreateData方法上来,并且传入key=1,data=100 
    11.         [OperationContract] 
    12.         [WebInvoke(UriTemplate = "Data/{key}/{data}", Method = "PUT", ResponseFormat = WebMessageFormat.Json)] 
    13.         void CreateData(string key, string data); 
    14.  
    15.         [OperationContract] 
    16.         [WebInvoke(UriTemplate = "Data/{key}", Method = "GET", ResponseFormat = WebMessageFormat.Json)] 
    17.         string RetrieveData(string key); 
    18.  
    19.         [OperationContract] 
    20.         [WebInvoke(UriTemplate = "Data/{key}/{data}", Method = "POST", ResponseFormat = WebMessageFormat.Json)] 
    21.         void UpdateData(string key, string data); 
    22.  
    23.         [OperationContract] 
    24.         [WebInvoke(UriTemplate = "Data/{key}", Method = "DELETE", ResponseFormat = WebMessageFormat.Json)] 
    25.         void DeleteData(string key); 
    26.     } 

    然后是实现类,这个简单,没什么可说的。

    1. using System; 
    2. using System.Collections.Generic; 
    3. using System.ServiceModel; 
    4.  
    5. namespace Server 
    6.     //这个例子中用了Single Instance模式,这样m_DataDict的值才能保留住 
    7.     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
    8.     public class DataProvider : IData 
    9.     { 
    10.         private Dictionary<stringstring> m_DataDict = new Dictionary<stringstring>(); 
    11.  
    12.         public void CreateData(string key, string data) 
    13.         { 
    14.             m_DataDict[key] = data; 
    15.         } 
    16.  
    17.         public string RetrieveData(string key) 
    18.         { 
    19.             return m_DataDict.ContainsKey(key) ? m_DataDict[key] : "NOT FOUND"
    20.         } 
    21.  
    22.         public void UpdateData(string key, string data) 
    23.         { 
    24.             m_DataDict[key] = data; 
    25.         } 
    26.  
    27.         public void DeleteData(string key) 
    28.         { 
    29.             m_DataDict.Remove(key); 
    30.         } 
    31.     } 

    配置文件最关键了,注意里面绿色的注释部分:

    1. <?xml version="1.0" encoding="utf-8" ?> 
    2. <configuration> 
    3.     <system.serviceModel> 
    4.         <services> 
    5.             <service name="Server.DataProvider"> 
    6.          <!--必须使用webHttpBinding,而且要定义此endpoint的behaviorConfiguration(见后)--> 
    7.                 <endpoint address="" binding="webHttpBinding" contract="Server.IData" behaviorConfiguration="restBehavior" /> 
    8.                 <host> 
    9.                     <baseAddresses> 
    10.                         <add baseAddress="http://localhost:8080/wcf" /> 
    11.                     </baseAddresses> 
    12.                 </host> 
    13.             </service> 
    14.         </services> 
    15.  
    16.         <behaviors> 
    17.          <!--定义endpoint的behavior,webHttp节点表示启用web方式访问,这对REST是非常关键的--> 
    18.             <endpointBehaviors> 
    19.                 <behavior name="restBehavior"> 
    20.                     <webHttp/> 
    21.                 </behavior> 
    22.             </endpointBehaviors> 
    23.         </behaviors> 
    24.     </system.serviceModel> 
    25. </configuration> 

    最后发布服务,没什么特殊的,和以前一样:

    1. using System; 
    2. using System.ServiceModel; 
    3.  
    4. namespace Server 
    5.     class Program 
    6.     { 
    7.         static void Main(string[] args) 
    8.         { 
    9.             using(ServiceHost host = new ServiceHost(typeof(Server.DataProvider))) 
    10.             { 
    11.                 host.Open(); 
    12.                 Console.WriteLine("Running ..."); 
    13.                 Console.ReadKey(); 
    14.                 host.Close(); 
    15.             } 
    16.         } 
    17.     } 

    这个服务端没有用IIS做HOST,直接用自己的进程做的宿主(当然了,本质还是http.sys在工作)。


    2、客户端

    我们这回要用REST形式访问服务端,所以不是普通意义上的WCF客户端了,再也用不着那么麻烦的写配置文件创建Channel或者代理了。

    1. using System; 
    2. using System.Net; 
    3.  
    4. namespace Client 
    5.     class Program 
    6.     { 
    7.         static void Main(string[] args) 
    8.         { 
    9.          //用一个WebClient就可以搞定了 
    10.             var client = new WebClient(); 
    11.  
    12.      //以PUT方式访问Data/1/100,会映射到服务端的CreateData("1", "100") 
    13.      client.UploadString("http://localhost:8080/wcf/Data/1/100""PUT"string.Empty); 
    14.  
    15.      //以GET方式访问Data/1,会映射到服务端的RetrieveData("1"),应该返回"100" 
    16.      Console.WriteLine(client.DownloadString("http://localhost:8080/wcf/Data/1")); 
    17.  
    18.      //以POST方式访问Data/1/200,会映射到服务端的UpdateData("1", "200")             
    19.     client.UploadString("http://localhost:8080/wcf/Data/1/200""POST"string.Empty); 
    20.  
    21.      //再GET一次,应该返回"200" 
    22.      Console.WriteLine(client.DownloadString("http://localhost:8080/wcf/Data/1")); 
    23.  
    24.      //以DELETE方式访问Data/1,会映射到服务端的DeleteData("1") 
    25.      client.UploadString("http://localhost:8080/wcf/Data/1""DELETE"string.Empty); 
    26.  
    27.      //再GET一次,应该返回"NOT FOUND" 
    28.          Console.WriteLine(client.DownloadString("http://localhost:8080/wcf/Data/1")); 
    29.         } 
    30.     } 

     

    需要补充一下,如果用IIS做HOST,比如DataService.svc.cs是实现类,一定要在DataService.svc中加上Factory,如下:

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

    表明不是使用默认的ServiceHostFactory,而是适应WEB HTTP开发的WebServiceHostFactory。

    本文出自 “兔子窝” 博客,请务必保留此出处http://boytnt.blog.51cto.com/966121/860724

  • 相关阅读:
    mybatis 错误 Invalid bound statement (not found)
    Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.
    bug 记录 Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans
    解决:The Tomcat connector configured to listen on port 8182 failed to start. The port may already be in use or the connector may be misconfigured.
    jquery validate 验证插件 解决多个相同的Name 只验证第一个的方案
    phpStorm+xdebug调试(php7.3)
    小程序视频多个视频播放与暂停
    CSS实现单行、多行文本溢出显示省略号(…)
    Packet for query is too large (4,544,730 > 4,194,304). You can change this value on the server by setting the 'max_allowed_packet' variable.
    idea自动在文件头中添加作者和创建时间
  • 原文地址:https://www.cnblogs.com/blog4xy/p/3644691.html
Copyright © 2011-2022 走看看