先从SoapHeader继承一个自定义类CredentialSoapHeader,该类包含用户名和密码:
public class CredentialSoapHeader : SoapHeader
{
public string Username
{
get { }
set { }
}
public string Password
{
get { }
set { }
}
}
{
public string Username
{
get { }
set { }
}
public string Password
{
get { }
set { }
}
}
在WebService类里面创建一个属性Credentials,类型为CredentialSoapHeader:
public class IssueVisionServices : WebService
{
// custom SOAP header to pass credentials
public CredentialSoapHeader Credentials
{
get { }
set { }
}
}
{
// custom SOAP header to pass credentials
public CredentialSoapHeader Credentials
{
get { }
set { }
}
}
在WebMethod的方法上使用SoapHeader标识,成员名称为"Credentials":
[WebMethod(Description="Returns the lookup tables for IssueVision.")]
[SoapHeader("Credentials")]
public IVDataSet GetLookupTables()
{
SecurityHelper.VerifyCredentials(this);
return new IVData().GetLookupTables();
}
[SoapHeader("Credentials")]
public IVDataSet GetLookupTables()
{
SecurityHelper.VerifyCredentials(this);
return new IVData().GetLookupTables();
}
public class SecurityHelper
{
// verifies the clients credentials
public static void VerifyCredentials(IssueVisionServices service)
{
String userName = service.Credentials.Username;
String password = service.Credentials.Password;
// 按照userName 和 password 进行授权验证
}
}
{
// verifies the clients credentials
public static void VerifyCredentials(IssueVisionServices service)
{
String userName = service.Credentials.Username;
String password = service.Credentials.Password;
// 按照userName 和 password 进行授权验证
}
}
二、客户端对Web Service的调用
private static IssueVisionServices GetWebServiceReference()
{
return GetWebServiceReference(UserSettings.Instance.Username, UserSettings.Instance.Password);
}
private static IssueVisionServices GetWebServiceReference(string username, string password)
{
IssueVisionServices dataService = new IssueVisionServices();
//<ReplaceWithWse>
CredentialSoapHeader header = new CredentialSoapHeader();
header.Username = username;
header.Password = password;
dataService.CredentialSoapHeaderValue = header;
//</ReplaceWithWse>
InitWebServiceProxy(dataService);
return dataService;
}
{
return GetWebServiceReference(UserSettings.Instance.Username, UserSettings.Instance.Password);
}
private static IssueVisionServices GetWebServiceReference(string username, string password)
{
IssueVisionServices dataService = new IssueVisionServices();
//<ReplaceWithWse>
CredentialSoapHeader header = new CredentialSoapHeader();
header.Username = username;
header.Password = password;
dataService.CredentialSoapHeaderValue = header;
//</ReplaceWithWse>
InitWebServiceProxy(dataService);
return dataService;
}