如前一章節大部分一下,只是有如下部分不一樣
1,把第一節中的綁定的安全模式重新設定 如下
<!-- 加上下面的bindings 配置結點 開始--> <bindings > <wsHttpBinding > <binding name ="mybehaviorConfiguration"> <security mode ="Transport"> <transport clientCredentialType="Basic"/><!-- 這裡把驗證為空白改為了Basic--> </security> </binding> </wsHttpBinding> </bindings> <!-- 加上下面的bindings 配置結點 結束 -->
2,update service reference (更新一下用戶端設定檔app.config)
其實只改了一處地方:
由<transport clientCredentialType="None"
改<transport clientCredentialType="Basic"
3,用戶端增加驗證代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;/////////////////using System.Net.Security;///////////////using System.Security.Cryptography.X509Certificates;//加上X509認證命名空間namespace WCFClient{ class Program { static void Main(string[] args) { try { WCFServer.Service1Client wcfClient = new WCFClient.WCFServer.Service1Client(); string strReturn = "send to server String !!"; //在這裡做了身分識別驗證的動作 (在前一課的基礎上增加下面兩句) wcfClient.ClientCredentials.UserName.UserName = "Administrator"; wcfClient.ClientCredentials.UserName.Password = "aA"; //這下面這一步非常關鍵,它重寫了伺服器的驗證方法,即不要驗證,直接發送請求到伺服器端 //重寫驗證服務端認證的方法。 System.Net.ServicePointManager.ServerCertificateValidationCallback += MyCertificateValidate; strReturn = wcfClient.GetData(strReturn ); Console.Write(strReturn); Console.Read(); } catch (Exception e) { Console.WriteLine("Exception : {0}", e.Message); } Console.WriteLine("Press any key to exit"); Console.Read(); } private static bool MyCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { // trust any certificate!!! System.Console.WriteLine("Warning, trust any certificate"); return true; } }}
至此Windows身分識別驗證的WCF也完成了