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

    在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,否则不能正确显示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值