在項目開發的過程當中,WebService是常常要用的,當調用WebService方法時,須要通過服務的驗證才能夠調用,通常就是用戶名/密碼驗證,還有一個就是證書.下面程序使用的是用戶名/密碼的方式,很簡單的一個程序. 先看服務端的代碼(ws_Service) MySoapHeader.cs 這裏經過繼承SoapHeader實現對用戶名/密碼的驗證 public class MySoapHeader:System.Web.Services.Protocols.SoapHeader { private string userID = string.Empty; private string userPW = string.Empty; public string UserId { get { return userID; } set { userID = value; } } public string UserPW { get { return userPW; } set { userPW = value; } } public MySoapHeader() { } public MySoapHeader(string name, string password) { userID = name; userPW = password; } private bool IsValid(string nUserId, string nPassWord, out string nMsg) { nMsg = ""; try { if (nUserId == "admin" && nPassWord == "admin") { return true; } else { nMsg = "對不起,你無權調用Web服務"; return false; } } catch { nMsg = "對不起,你無權調用Web服務"; return false; } } public bool IsValid(out string nMsg) { return IsValid(userID,userPW,out nMsg); } } Service1.asmx文件代碼: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class Service1 : System.Web.Services.WebService { public MySoapHeader myHeader = new MySoapHeader(); [WebMethod] public string GetMsg() { Thread.Sleep(5000); return "Hello World"; } [SoapHeader("myHeader")] [WebMethod(Description="獲取用戶列表")] public string GetMain() { string msg = ""; if (!myHeader.IsValid(out msg)) { return msg; } return "Main"; } } 這裏面有兩個方法,其中GetMsg方法是不須要驗證的,而GetMain方法須要進行用戶名/密碼的驗證,這個能夠在客戶端調用時進行驗證. 客戶端添加對服務端的引用… Program.cs文件 class Program { static void Main(string[] args) { localhost.Service1SoapClient proxy = new ws_Client.localhost.Service1SoapClient(); MySoapHeader header = new MySoapHeader(); header.UserId = "admin"; header.UserPW = "admin"; string result = proxy.GetMain(header); //string result = proxy.GetMsg(); Console.WriteLine(result); Console.ReadKey(); } }