65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 2.0 的 CookieParameter 的附加功能

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (3投票s)

2004年11月6日

2分钟阅读

viewsIcon

59158

downloadIcon

440

本文解决了 ASP.NET 2.0 的 CookieParameter 类型中缺少的一些功能,包括获取多值 Cookie 的 Key 值以及提供一些 HttpCookieEncryption 支持。

引言

ASP.NET 2.0 的 CookieParameter 是一个很好的起点,可以将 HTTP 数据直接提供给 DataSource 控件,包括 SqlDataSource 和其他各种变体。

然而,在我看来,代码中存在两个明显的遗漏,包括提取多值 Cookie 中的键值能力。(请参阅 HttpCookie.Values 集合,提供名称-值对分组。)

此外,我之前的文章介绍了 HttpCookieEncryption,这是一种防止篡改 Cookie 数据的方法。请注意,通过 HttpCookieEncryption 提供的加密仅在合理范围内保证防篡改,但可能被查看,因此,敏感数据仍然应存储在 Session 状态或某种不传输到客户端的介质中。

使用新的改进的 CookieParameter (CookieParameterEx)

由于 DataControl 构建器不支持向对话框中添加新的“Parameter”类型,因此不幸的是,我们必须诉诸代码编辑器才能真正使用 CookieParameterEx 的修改。因此,我建议使用 DataControl 构建器指定参数等,然后手动将 CookieParameter 引用更改为 CookieParameterEx

因此,在 HttpCookieEncryption 的基础上(并且由于 ASP.NET 2.0 中的一些类型更改进行了一些调整),我正在引入对 CookieParameter 的扩展。

CookieParameterEx,CookieParameter 的扩展

CookieParameterEx 子类化了 System.Web.UI.WebControls.CookieParameter 类型。它添加了一些新的构造函数重载,但最重要的是添加了两个新的属性:KeyIsEncrypted

IsEncrypted 属性利用 HttpCookieEncryption.Decrypt 首先解密 Cookie,然后能够检查 Cookie 的值或键值。

Key 属性指定为 CookieParameterEx.CookieName 指定的 Cookie 是一个多值 Cookie,并且应该查看其中一个值,而不是整个 HttpCookie.Value

实际工作是在 DataSource 控件(间接)调用控件的 Evaluate 方法时完成的

protected override object Evaluate(System.Web.HttpContext context, 
                              System.Web.UI.Control control)
{
    //defer to base if neither of the newer properties are set.
    if( this.CookieName == null && this.IsEncrypted==false )
        return base.Evaluate(context, control);

    HttpCookie cookie1 = context.Request.Cookies[this.CookieName];
    if (cookie1 == null)
    {
        return null;
    }

    // decrypt the cookie if the IsEncrypted flag is true.
    if (this.IsEncrypted)
    {
        HttpCookie cookie2 = HttpCookieEncryption.Decrypt(cookie1);

        // cookie2 will be null if the HexToString
        // can't "DeHex" the current value.
        // so only change to a non-null decrypted cookie.
        if (cookie2 != null) cookie1 = cookie2;
    }

    // use the Key 
    if (this.Key != null)
        return cookie1[this.Key];
    else
        return cookie1.Value;
}

现在我们拥有一个防篡改的 Cookie,可以在 DataSource 控件中使用。

© . All rights reserved.