WCF4.0 -- RESTful WCF Services(创建基于SSL的服务)

来源:互联网 发布:哈尔滨工程大学网络 编辑:程序博客网 时间:2024/06/07 11:58

其实这个标题和WCF本身关系不大,因为REST WCF服务一般寄宿于IIS,而SSL是传输层的事儿,说白了就是IIS的事。
首先创建个简单的REST WCF服务:(使用 WCF REST Service Application 模板)

[c-sharp] view plaincopyprint?
  1. [ServiceContract] 
  2. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
  3. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
  4. public class Service1 
  5.     [WebGet(UriTemplate="GetHello")] 
  6.     public string GetHello() 
  7.     { 
  8.         return "Hello Client by Get"
  9.     } 
  10.  
  11.     [WebInvoke(UriTemplate = "PostHello", Method="POST")] 
  12.     public string PostHello() 
  13.     { 
  14.         return "Hello Client by Post"
  15.     } 

服务很简单,就是为了让客户端通过HttpRequst在SSL下能访问到就行。

IIS6的配置: 在网站根目录下选"Directory Security">"Server Certificate...">Next>Assign an existing certificate
然后选一个自己已经准备好的证书就可以了。如何生成证书就不说了,网上自己搜搜吧。

IIS7的配置:
1.在IIS7里可以直接创建新证书:


为了测试,生成自签名的证书。



接下来需要为IIS设置Https Binding和证书


设置完毕后,在Default Web Site下的所有Application都可以通过两种方式来访问:Http或Https
如果需要设置只能通过Https访问,还需要到指定的Application上设置下SSL Settings,让该Application要求SSL:

现在直接通过IE来访问这个WCF服务,可以看到如下的效果:

因为生成的服务端证书是自签名的(没有第3方认证)所以被浏览器拦截了。问你是否要继续访问,点继续访问就可以看到结果了。


OK,再来看看客户端如何调用:

[c-sharp] view plaincopyprint?
  1. static void Main(string[] args) 
  2.     var url = "https://earthqa-pc/Service1/gethello"
  3.     try 
  4.     { 
  5. ServicePointManager.ServerCertificateValidationCallback += 
  6.             new RemoteCertificateValidationCallback(allowCert); 
  7.         WebClient wc = new WebClient(); 
  8.         var str = wc.DownloadString(url); 
  9.         Console.WriteLine(str); 
  10.     } 
  11.     catch (Exception ex) 
  12.     { 
  13.         Console.WriteLine("Error: {0}", ex.Message); 
  14.     } 
  15.     Console.ReadLine(); 
  16.  
  17. private staticbool allowCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) 
  18.     var request = sender as HttpWebRequest; 
  19.     Console.WriteLine(request.Address.Host); 
  20.     //Console.WriteLine(cert.Subject); 
  21.     return true

因为没有客户端证书,所以客户端只需要承认下服务端证书即可:在 ServicePointManager.ServerCertificateValidationCallback 事件中,返回true即可。
原创粉丝点击