对于WebService调用,为了验证调用者的身份,可以自定义一个SoapHeader,让调用者将身份信息放在里面,然后在服务端检查,具体方法如下:
1、先定义一个SoapHeader,用它来传递身份信息:
- using System;
- using System.Web.Services.Protocols;
-
- namespace CustomSoap
- {
-
-
-
- public class ServiceHeader : SoapHeader
- {
-
-
-
- public string Name { get; set; }
-
-
-
- public string Pass { get; set; }
- }
- }
2、WebService中的服务方法要修改一下:
- using System;
- using System.Web.Services;
- using System.Web.Services.Protocols;
-
- namespace CustomSoap
- {
- [WebService(Namespace = "CustomSoap.Test")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- public class Service : System.Web.Services.WebService
- {
-
-
-
- public ServiceHeader Header { get; set; }
-
-
-
-
-
- [WebMethod]
- [SoapHeader("Header")]
- public string Hello()
- {
- string user = this.Header.Name;
- string pass = this.Header.Pass;
-
-
- if(string.Equals(user, "root") && string.Equals(pass, "pass"))
- return "Hello root";
- else
- return "Login Required";
- }
- }
- }
3、调用者要传递身份信息:
- public string CallHello()
- {
-
- var proxy = new CustomSoap.Remote.ServiceProxy();
-
-
- proxy.ServiceHeaderValue = new CustomSoap.Remote.ServiceHeader();
- proxy.ServiceHeaderValue.Name = "root";
- proxy.ServiceHeaderValue.Pass = "pass";
-
-
- return proxy.Hello();
- }
调用一下,应该能收到“Hello root”,如果用户名或密码错误,会收到“Login Required”。
此时的SOAP内容会发生变化,抓一下包或者直接在浏览器上访问Service.asmx?op=Hello,可以看到请求包:
- POST /Service.asmx HTTP/1.1
- Host: localhost
- Content-Type: text/xml; charset=utf-8
- Content-Length: length
- SOAPAction: "CustomSoap.Test/Hello"
-
- <?xml version="1.0" encoding="utf-8"?>
- <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
-
- <soap:Header>
- <ServiceHeader xmlns="CustomSoap.Test">
- <Name>string</Name>
- <Pass>string</Pass>
- </ServiceHeader>
- </soap:Header>
- <!--END-->
- <soap:Body>
- <Hello xmlns="CustomSoap.Test" />
- </soap:Body>
- </soap:Envelope>
另外提一下,对于WebService,是明文的SOAP通讯,安全性上需要各位自己考虑一下方案。
本文转自 BoyTNT 51CTO博客,原文链接:http://blog.51cto.com/boytnt/837345,如需转载请自行联系原作者