1:自定义SoapHeader类,继承自:System.Web.Services.Protocols.SoapHeader
using System;
using System.Collections.Generic;
using System.Web;
/// <summary>
///自定义的SoapHeader
/// </summary>
public class MySoapHeader : System.Web.Services.Protocols.SoapHeader
{
private string userName=string.Empty;
private string passWord=string.Empty;
/// <summary>
/// 构造函数
/// </summary>
public MySoapHeader() { } /// <summary>
/// 构造函数
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
public MySoapHeader(string userName, string passWord)
{
this.userName = userName;
this.passWord = passWord;
}
/// <summary>
/// 获取或设置用户用户名
/// </summary>
public string UserName
{
get { return userName; }
set { userName = value; }
}
/// <summary>
/// 获取或设置用户密码
/// </summary>
public string PassWord
{
get { return passWord; }
set { passWord = value; }
}
}
2:定义webservice
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
//声明Soap头实例
public MySoapHeader myHeader=new MySoapHeader();
//原来声明webmethod 时,只要一个[WebMethod],现在需要再加一个[SoapHeader("myHeader")]
[System.Web.Services.Protocols.SoapHeader("myHeader")]
[WebMethod]
public string HelloWord()
{
//可以通过存储在数据库中的用户与密码来验证
if (myHeader.UserName.Equals("test")&myHeader.PassWord.Equals("test"))
{
return "调用服务成功!";
}
else
{
return "对不起,您没有权限调用此服务!";
}
}
}
3:使用SoapHeader调用webservice
3.客户端调用,分别使用不设置SoapHeader与设置SoapHeader。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace App { class Program { static void Main(string[] args) { localhost.WebService service = new localhost.WebService(); //没有设置SoapHeader的服务调用 Console.WriteLine("没有设置SoapHeader:" + service.HelloWord()); Console.WriteLine(); //将用户名与密码存入SoapHeader; localhost.MySoapHeader header = new localhost.MySoapHeader(); header.UserName = "test"; header.PassWord = "test"; service.MySoapHeaderValue = header; //设置SoapHeader的服务调用 Console.WriteLine("设置SoapHeader:" + service.HelloWord()); Console.Read(); } } }
只有验证成功才能进行调用webservice,否则就会提示没有权限。