服务端
using
System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
// 如果使用设计的组件,请取消注释以下行
// InitializeComponent();
}
public MySoapHeader mh;
[WebMethod, SoapHeader( " mh " )]
public string HelloWorld()
{
IsValid();
return " Hello World " ;
}
private bool IsValid()
{
if ( this .mh == null
|| this .mh.Username == null
|| this .mh.Password == null )
{
throw new SoapException( " 没有提供信任令牌 " ,
SoapException.ClientFaultCode, " Security " );
}
// TODO:添加自定义验证
return true ;
}
}
/// <summary>
/// 定义SoapHeader.
/// </summary>
public class MySoapHeader : SoapHeader
{
public string Username;
public string Password;
}
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
// 如果使用设计的组件,请取消注释以下行
// InitializeComponent();
}
public MySoapHeader mh;
[WebMethod, SoapHeader( " mh " )]
public string HelloWorld()
{
IsValid();
return " Hello World " ;
}
private bool IsValid()
{
if ( this .mh == null
|| this .mh.Username == null
|| this .mh.Password == null )
{
throw new SoapException( " 没有提供信任令牌 " ,
SoapException.ClientFaultCode, " Security " );
}
// TODO:添加自定义验证
return true ;
}
}
/// <summary>
/// 定义SoapHeader.
/// </summary>
public class MySoapHeader : SoapHeader
{
public string Username;
public string Password;
}
客户端
private
void
button1_Click(
object
sender, EventArgs e)
{
try
{
localhost.MySoapHeader m = new WindowsApplication1.localhost.MySoapHeader();
m.Username = " test " ;
m.Password = " test " ;
localhost.Service s = new WindowsApplication1.localhost.Service();
s.MySoapHeaderValue = m;
MessageBox.Show(s.HelloWorld());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
{
try
{
localhost.MySoapHeader m = new WindowsApplication1.localhost.MySoapHeader();
m.Username = " test " ;
m.Password = " test " ;
localhost.Service s = new WindowsApplication1.localhost.Service();
s.MySoapHeaderValue = m;
MessageBox.Show(s.HelloWorld());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}