asp.net 2.0中傻瓜式使用soap header

來源:互聯網
上載者:User

在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,否則不能正確顯示

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.