PRB: A NULL Value Is Returned for Cookies That Do Not Exist (314461)
The information in this article applies to:
- Microsoft ASP.NET (included with the .NET Framework 1.1)
- Microsoft ASP.NET (included with the .NET Framework) 1.0
This article was previously published under Q314461 SYMPTOMS
When you reference a cookie that does not exist in ASP.NET code, you may receive an error message that is similar to the following:
System.NullReferenceException: Object reference not set to an instance of an object.
CAUSE
This behavior can occur because a NULL value is received when you request a cookie that does not exist in ASP.NET. This is consistent with how managed collections work in ASP.NET. In ASP Classic, the request object returns an empty string if a requested cookie does not exist.
RESOLUTION
To resolve this behavior, check for NULL values that are associated with cookies, as shown in the following sample codes:
Microsoft Visual C# .NET
HttpCookie cookie = Request.Cookies["SomeCookie"];
if(cookie == null)
{
//CookieValue represents a WebForm Label control
CookieValue.Text = "Cookie does not exist!";
}
else
{
//CookieValue represents a WebForm Label control
CookieValue.Text = cookie.Value;
}
Microsoft Visual Basic .NET
Dim cookie As HttpCookie = Request.Cookies("SomeCookie")
If cookie Is Nothing Then
'CookieValue represents a WebForm Label control
CookieValue.Text = "Cookie does not exist!"
Else
'CookieValue represents a WebForm Label control
CookieValue.Text = cookie.Value
End If
STATUSThis behavior is by design.REFERENCES
For more information about the HTTPCookie class, the HTTPCookieCollection class, and the exhibited behavior for the cookie collection that is described in this article, visit the following Microsoft Web sites:
Modification Type: | Minor | Last Reviewed: | 7/11/2003 |
---|
Keywords: | kbCookie kberrmsg kbprb kbState KB314461 kbAudDeveloper |
---|
|