对于WebService调用,为了验证调用者的身份,可以自定义一个SoapHeader,让调用者将身份信息放在里面,然后在服务端检查,具体方法如下:

1、先定义一个SoapHeader,用它来传递身份信息:

usingSystem;usingSystem.Web.Services.Protocols;namespaceCustomSoap{///<summary>///自定义SOAP头,从SoapHeader派生///</summary>publicclassServiceHeader:SoapHeader{///<summary>///定义用户名字段///</summary>publicstringName{get;set;}///<summary>///定义密码字段///</summary>publicstringPass{get;set;}}}


2、WebService中的服务方法要修改一下:

usingSystem;usingSystem.Web.Services;usingSystem.Web.Services.Protocols;namespaceCustomSoap{[WebService(Namespace="CustomSoap.Test")][WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)][System.ComponentModel.ToolboxItem(false)]publicclassService:System.Web.Services.WebService{///<summary>///定义一个ServiceHeader对象///</summary>publicServiceHeaderHeader{get;set;}///<summary>///服务方法,用SoapHeader标记使用哪个头,此处是上面定义的Header属性///</summary>///<returns></returns>[WebMethod][SoapHeader("Header")]publicstringHello(){stringuser=this.Header.Name;stringpass=this.Header.Pass;//在此处可以进行身份判断,这里是写死了用户名密码if(string.Equals(user,"root")&&string.Equals(pass,"pass"))return"Helloroot";elsereturn"LoginRequired";}}}


3、调用者要传递身份信息:

publicstringCallHello(){ //ServiceProxy是针对Service.asmx生成的代理类varproxy=newCustomSoap.Remote.ServiceProxy(); //传递身份信息proxy.ServiceHeaderValue=newCustomSoap.Remote.ServiceHeader();proxy.ServiceHeaderValue.Name="root";proxy.ServiceHeaderValue.Pass="pass"; //调用远程方法returnproxy.Hello();}

调用一下,应该能收到“Hello root”,如果用户名或密码错误,会收到“Login Required”。


此时的SOAP内容会发生变化,抓一下包或者直接在浏览器上访问Service.asmx?op=Hello,可以看到请求包:

POST/Service.asmxHTTP/1.1Host:localhostContent-Type:text/xml;charset=utf-8Content-Length:lengthSOAPAction:"CustomSoap.Test/Hello"<?xmlversion="1.0"encoding="utf-8"?><soap:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <!--这里多出来了Header,内容就是我们自定义的ServiceHeader--><soap:Header><ServiceHeaderxmlns="CustomSoap.Test"><Name>string</Name><Pass>string</Pass></ServiceHeader></soap:Header> <!--END--><soap:Body><Helloxmlns="CustomSoap.Test"/></soap:Body></soap:Envelope>


另外提一下,对于WebService,是明文的SOAP通讯,安全性上需要各位自己考虑一下方案。