在websevrice 中,soap header是十分重要的哦,主要是安全性的考慮,在asp.net 2.0中,可以簡單地應用soap header來
進行傻瓜式的應用,更複雜的應用當然要更深入地去看了,
首先,我們寫個簡單的helloworld的webservice
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 ValidationSoapHeader Authentication;
private const string DEV_TOKEN = "12345";
public Service()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[SoapHeader("Authentication")]
[WebMethod]
public string HelloWorld()
{
if (Authentication != null && Authentication.DevToken == DEV_TOKEN)
{
return "Hello World";
}
else
{
throw new Exception("Authentication Failed");
}
}
}
可以看到,首先必須在[webmethod]前添加[SoapHeader("Authentication")],這裡我們判斷來自用戶端的soap header是否有效,並且看其tokern是否等於我們預先定義好的token,如果是的話就輸出hello world,否則拋出異常
這裡我們編寫一個ValidationSoapHeader類,其中是繼承了soap header,如下
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services.Protocols;
/// <summary>
/// Summary description for ePhoneCredentials
/// </summary>
public class ValidationSoapHeader : SoapHeader
{
private string _devToken;
public ValidationSoapHeader()
{
}
public ValidationSoapHeader(string devToken)
{
this._devToken = devToken;
}
public string DevToken
{
get { return this._devToken; }
set { this._devToken = value; }
}
}
這裡只不過是一些屬性的設定讀取,然後編寫一個用戶端,如下,顯式指定要傳遞soap header
//ConsoleMyCsharpClient是建立用戶端的工程名
localhost.ValidationSoapHeader header = new ConsoleMyCsharpClient.localhost.ValidationSoapHeader();
header.DevToken = "12345";
localhost.Service ws = new ConsoleMyCsharpClient.localhost.Service();
ws.ValidationSoapHeaderValue = header;
Console.WriteLine(ws.HelloWorld());
Console.ReadLine();
這樣,當用戶端傳遞12345給WS後,能正確顯示HELLO WORLD,否則不能正確顯示