一、首先在webservice的APP_code下建立自定义类,该类继承需要引入两个命名空间
System.Web.Services;
System.Web.Services.Protocols;
二、该类需要继承System.Web.Services.Protocols命名空间下的SoapHeader 类,暂且将该类命名为MySoapHeader
三、在该类(MySoapHeader)下写验证方法,用来接收报头信息,进行身份验证,判断是否有权使用webservice,一般该方法返回bool值。这里该类下有两个私有字段,并且设置了字段的读写属性,用来接收用户名和密码。
public class MySoapHeader:SoapHeader
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string pwd;
public string Pwd
{
get { return pwd; }
set { pwd = value; }
}
public bool CanUseServer(string nUserId, string nUserPwd)
{
try
{
if (nUserId == "dufy" && nUserPwd == "dufy")
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public bool CanUseServer()
{
return CanUseServer(name, pwd);
}
四、在webservice中声明上面自己定义的类的实例,切忌不能用new实例化。然后给方法添加属性
public MySoapHeader soapHeader;
[SoapHeader("soapHeader",Direction=SoapHeaderDirection.InOut)]
[WebMethod(Description="建立带有报头的web服务",EnableSession=true)]
五、在方法中首先验证是否通过soap验证,如果通过验证,进行允许执行方法,如果没有通过方法验证,退出。
[SoapHeader("soapHeader",Direction=SoapHeaderDirection.InOut)]
[WebMethod(Description="建立带有报头的web服务",EnableSession=true)]
public int Add(int a, int b)
{
if(!soapHeader.CanUseServer())//判断是否通过验证
{
return 0;
}
return a + b;
}
以上是建立带有soap报头webservice的方法和注意事项。
下面是客户端调用的方法和注意事项。
一、添加对web服务的引用
二、建立报头的实例,并且给报头赋值
MySoapTest.MySoapHeader soap = new MySoapTest.MySoapHeader();
soap.Name = TextBox1.Text.Trim();
soap.Pwd = TextBox2.Text.Trim();
三、建立webservice的实例
MySoapTest.Service service = new MySoapTest.Service();
四、关联webservice和soap报头
service.MySoapHeaderValue = soap;
五、调用webservice方法,此时,如果身份验证通过,则可以成功调用,否则调用失败