在项目开发的过程中,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(); } }