webservice---SoapHeader头部认证
SoapHeader为webservice的头部信息,头部信息可用于相关的验证等功能
在webservice服务端定义SoapHeader类,继承自SoapHeader
/// <summary>
/// 用于webservice认证
/// </summary>
public class CertficateSoapHeader : SoapHeader
{
/// <summary>
/// 属性
/// </summary>
public string UserName { get; set; }
public string PassWord { get; set; }
public CertficateSoapHeader() { }
/// <summary>
/// 构造函数认证
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
public CertficateSoapHeader(string userName, string passWord)
{
this.UserName = userName;
this.PassWord = passWord;
}
}
服务类中:
public class BotWebService : System.Web.Services.WebService
{
public CertficateSoapHeader soapHeader;
[SoapHeader("soapHeader",Direction=SoapHeaderDirection.In)]//这里的声明必需和上次的名字对应
[WebMethod]
public string HelloWorld()
{
if (myHeader.UserName == null || myHeader.PassWord == null)
{
break;
}
if (myHeader.UserName.Equals("LY") && myHeader.PassWord.Equals("LY"))
{
return "Hello World";
break;
}
else
{
throw new SoapHeaderException("认证失败", SoapException.ClientFaultCode);}
}
客户端调用:
BotWebServiceSoapClient service = new BotWebServiceSoapClient();
// BotWebService service = new BotWebService();
CertficateSoapHeader header = new CertficateSoapHeader();
header.UserName = "LY";
header.PassWord = "LY";
service.CertficateSoapHeaderValue = header;
string aa = service.HelloWorld(header);
这样就能正常返回,如果不定义,就不能认证
这种方式实现起来比较简单,但在webservice中每个webmethod方法中都必须加上if。。else。。的判断条件,使用起来不够灵活,从软件设计的角度讲藕合性太强,
一般的权限认证和日志认证,一般会用动态代理来处理相关问题. 而在webservice中一般用SoapExtensionAttribute和SoapExtension方法来处理。