Home > .NET > Response.Cookies Bug

Response.Cookies Bug

April 30th, 2004

Admittedly, I am no Brad Abrams when it comes to API design and usage but I am pretty sure that this API faux pas constitutes itself as a bug.  The bug is in HttpCookie and has to do with the Value and Values properties.  You can use the following code to reproduce the bug:

private void Page_Load(object sender, System.EventArgs e)
{
Response.Write(Response.Cookies[ "cooookie" ].Value == null);
Response.Write(”");
Response.Write(Response.Cookies[ "cooookie" ].Values.ToString());
Response.Write(”");
Response.Write(Response.Cookies[ "cooookie" ].Value == null);
}

By looking at the code you would expect the output of the page to be:

True

True

However, it wouldn’t be a very good bug if it were to work as expected.  Instead of the above you get:

True

False

So how can this be?  Why would merely reading the value of the Values property change the value in Value property?  The problem is actually somewhat interesting and has to do with way these two properties try and show you the same thing (which begs the question as to why you need them both?).  If you look at the framework code for HttpCookie you’ll see that the bug is in the way the getters work.

First. look at the getter for the Value property.  Here is (essentially) the code for that getter (_multiValue is a private HttpValueCollection used by the Values property) :

get
{
if (this._multiValue != null)
{
return this._multiValue.ToString(0);
}
return this._stringValue;
}

The idea here is to show a string representation of the HttpValueCollection if we have one and if not, then show the single string value.  Next look at the getter for the Values property:

get
{
if (this._multiValue == null)
{
this._multiValue = new HttpValueCollection();
if (this._stringValue != null)
{
// some code to add it
}
}
return this._multiValue;
}

You can see that the key point here is that the property creates an instance of _multiValue if one does not exist.  This is bad for the other property (Value) because that was our condition to determine what to output.  But why does this matter?  It only matters because we are using ToString(bool) on the HttpValueCollection which returns “” when the value is null!  This is why our return value changes upon getting the Values property.  I guess a better way to do this would be to use the same private variable for both properties since they are attempting to represent the same thing.  So you would create an instance of the collection in the setter of Value and just add the value there.

.NET

  1. No comments yet.
  1. No trackbacks yet.