In the process of project development, WebService is often used, when the WebService method is called, it needs to be validated by the service to be called, generally is the user name/password authentication, there is a certificate. The following program uses a username/password in a way that is very simple for a program.first look at the server code (WS_SERVICE) MySoapHeader.cs here by inheriting SoapHeader implementation of the user name/Authentication of Passwords Public classMySoapHeader:System.Web.Services.Protocols.SoapHeader {Private stringUserID =string. Empty; Private stringUSERPW =string. Empty; Public stringUserId {Get{returnUserID;} Set{UserID =value;} } Public stringUSERPW {Get{returnUSERPW;} Set{USERPW =value;} } PublicMysoapheader () {} PublicMysoapheader (stringNamestringpassword) {UserID=name; USERPW=password; } Private BOOLIsValid (stringNuserid,stringNpassword, out stringnmsg) {nmsg=""; Try { if(Nuserid = ="Admin"&& Npassword = ="Admin") { return true; } Else{nmsg="Sorry, you don't have permission to invoke the Web service"; return false; } } Catch{nmsg="Sorry, you don't have permission to invoke the Web service"; return false; } } Public BOOLIsValid ( out stringnmsg) { returnIsValid (USERID,USERPW, outnmsg); }}service1.asmx File code: [WebService (Namespace="http://tempuri.org/")][webservicebinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)] Public classservice1:system.web.services.webservice{ PublicMysoapheader MyHeader =NewMysoapheader (); [WebMethod] Public stringgetmsg () {Thread.Sleep ( the); return "Hello World"; } [SoapHeader ("MyHeader")] [WebMethod (Description="get a list of users")] Public stringGetmain () {stringmsg =""; if(!myheader.isvalid ( outmsg)) { returnmsg; } return "Main"; There are two methods in this, where the Getmsg method does not need to be validated, and the Getmain method requires a username/The authentication of the password, which can be verified when the client invokes it. Client adds a reference to the server ... Program.cs fileclassprogram{Static voidMain (string[] args) {localhost. Service1soapclient Proxy=Newws_Client.localhost.Service1SoapClient (); Mysoapheader Header=NewMysoapheader (); Header. UserId="Admin"; Header. USERPW="Admin"; stringresult =Proxy. Getmain (header); //string result = Proxy. Getmsg ();Console.WriteLine (Result); Console.readkey (); }}
WebService with User name password verification (for review)