提供一種基於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); } }
webservice穿插引用soapHeader:
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的注釋。 // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { public MySoapHeader myheader = new MySoapHeader(); [WebMethod] public string HelloWorld() { return "Hello World"; } //該地方是調用SoapHeader地方,注意觀察 [SoapHeader("myheader")] [WebMethod(Description="Say Hello My World")] public string HelloWorld2() { string msg = ""; if (!myheader.IsValid(out msg)) { return msg; } return "Hello World"; } }
客服端動態調用Webservice的方法,可以參考上篇博客
普通添加引用WEBSERVICE調用的方式代碼如下:
static void Main(string[] args) { MyService.WebService1SoapClient cmlent = new MyService.WebService1SoapClient(); MyService.MySoapHeader hro=new MyService.MySoapHeader (); hro.UserId="admin"; hro.UserPW="admin"; string rsult=cmlent.HelloWorld2(hro); Console.WriteLine(rsult); Console.ReadKey(); }