jackyrong

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
    在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,否则不能正确显示

posted on 2007-05-23 22:00  jackyrong的世界  阅读(6856)  评论(1编辑  收藏  举报