Introduction
The ASP.NET 2.0's CookieParameter
is a good start to providing HTTP data directly to the DataSource controls, including SqlDataSource
and the various other flavors.
However, in my opinion, there were two glaring omissions from the code, including the ability to extract a keyed value in a multi-valued cookie. (See HttpCookie.Values
collection, providing a name-value pair grouping.)
Additionally, my last article introduced HttpCookieEncryption, a way to prevent tampering of cookie data. Note that the encryption provided via HttpCookieEncryption
is only reasonably guaranteed to be tamper proof, but may be viewable, so again, sensitive data should still be stored in Session state or some kind of medium that does not get transmitted to the client.
Using the new and improved CookieParameter (CookieParameterEx)
Since the DataControl builders don't support adding new "Parameter" types to the dialog, we unfortunately have to resort to the Code editor to truly use the CookieParameterEx
modifications. So, I'd recommend using the DataControl builder to specify the parameters and such, then manually change the CookieParameter
references to CookieParameterEx
.
So building on the HttpCookieEncryption
(and doing a little fiddling because of a couple of type changes in ASP.NET 2.0), I'm introducing an extension to the CookieParameter
.
CookieParameterEx, an extension to CookieParameter
CookieParameterEx
subclasses the System.Web.UI.WebControls.CookieParameter
type. It adds a few new constructor overloads, but most notably adds two new properties: Key
and IsEncrypted
.
The IsEncrypted
property leverages HttpCookieEncryption.Decrypt
to first decrypt the cookie, then be able to inspect the value or keyed-values of the cookie.
The Key
property specifies that the cookie specified for CookieParameterEx.CookieName
is a multi-valued cookie, and should look at one of the values, instead of the entire HttpCookie.Value
.
The real work is done when DataSource controls (indirectly) call the control's Evaluate
method:
protected override object Evaluate(System.Web.HttpContext context,
System.Web.UI.Control control)
{
if( this.CookieName == null && this.IsEncrypted==false )
return base.Evaluate(context, control);
HttpCookie cookie1 = context.Request.Cookies[this.CookieName];
if (cookie1 == null)
{
return null;
}
if (this.IsEncrypted)
{
HttpCookie cookie2 = HttpCookieEncryption.Decrypt(cookie1);
if (cookie2 != null) cookie1 = cookie2;
}
if (this.Key != null)
return cookie1[this.Key];
else
return cookie1.Value;
}
We now have a tamper-secure cookie that can be used in DataSource controls.