使用soaphead方法可以在webservice的请求中增加头部信息,当有人调用我们的webservice时,可以通过查询这个请求的头部信息并验证来防止该软件以外的程序调用webservice
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using GB.BLL;
using GB.Utility;
using System.Web.Services.Protocols;
public class AuthHeaderGB : SoapHeader
{
public string Username;
public string Password;
}
/// <summary>
///UserService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class UserService : System.Web.Services.WebService
{
public AuthHeaderGB sHeader;
public UserService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod(Description = "获取用户信息")]
[SoapHeader("sHeader")]
public DataTable GetCompanyInfo(string userName)
{
if (sHeader == null)
{
return null;
}
else
{
string usr = sHeader.Username;
string pwd = sHeader.Password;
if (AuthenticateUser(usr, pwd))
{
CompanyBLL companyBLL = new CompanyBLL();
DataTable dt = companyBLL.GetCompanyInfo(userName);
return dt;
}
else
{
return null;
}
}
}
private bool AuthenticateUser(string usr, string pwd)
{
if ((usr != null&&pwd != null) && (usr=="gbwebservice"&&pwd=="gbpwd"))
{
return true;
}
return false;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using GB.BLL;
using GB.Utility;
using System.Web.Services.Protocols;
public class AuthHeaderGB : SoapHeader
{
public string Username;
public string Password;
}
/// <summary>
///UserService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class UserService : System.Web.Services.WebService
{
public AuthHeaderGB sHeader;
public UserService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod(Description = "获取用户信息")]
[SoapHeader("sHeader")]
public DataTable GetCompanyInfo(string userName)
{
if (sHeader == null)
{
return null;
}
else
{
string usr = sHeader.Username;
string pwd = sHeader.Password;
if (AuthenticateUser(usr, pwd))
{
CompanyBLL companyBLL = new CompanyBLL();
DataTable dt = companyBLL.GetCompanyInfo(userName);
return dt;
}
else
{
return null;
}
}
}
private bool AuthenticateUser(string usr, string pwd)
{
if ((usr != null&&pwd != null) && (usr=="gbwebservice"&&pwd=="gbpwd"))
{
return true;
}
return false;
}
}
调用
WebService webservice = new WebService();
AuthHeaderGB auth = new AuthHeaderGB();
auth.Username = "gbwebservice";
auth.Password = "gbpwd";
webservice.AuthHeaderGBValue = auth;
DataTable dt=auth.GetCompanyInfo("test");
AuthHeaderGB auth = new AuthHeaderGB();
auth.Username = "gbwebservice";
auth.Password = "gbpwd";
webservice.AuthHeaderGBValue = auth;
DataTable dt=auth.GetCompanyInfo("test");