Microsoft KB Archive/314461

= PRB: A NULL Value Is Returned for Cookies That Do Not Exist =

Article ID: 314461

Article Last Modified on 7/11/2003

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 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[&quot;SomeCookie&quot;];

if(cookie == null) {       //CookieValue represents a WebForm Label control CookieValue.Text = &quot;Cookie does not exist!&quot;; }   else {       //CookieValue represents a WebForm Label control CookieValue.Text = cookie.Value; }

Microsoft Visual Basic .NET
Dim cookie As HttpCookie = Request.Cookies(&quot;SomeCookie&quot;)

If cookie Is Nothing Then

'CookieValue represents a WebForm Label control CookieValue.Text = &quot;Cookie does not exist!&quot; Else

'CookieValue represents a WebForm Label control CookieValue.Text = cookie.Value End If



STATUS
This behavior is by design.



Steps to Reproduce the Behavior
 Add a new Web Form to your Visual Basic .NET or Visual C# .NET Web application as follows:  Open Visual Basic .NET. On the File menu, point to New, and then click Project. In the New Project dialog box, click Visual C# under Project Type, and then click ASP.NET Web Application under Templates. </li>  Add the following code to the Web Form:

Visual C# .NET <%@ Debug=true %> <script language=&quot;C#&quot; runat=&quot;server&quot;> void Page_Load(object sender, System.EventArgs e)    { txtUserName.Text = Request.Cookies[&quot;testing&quot;].Value.ToString; }   <form runat=server ID=&quot;Form1&quot;> <asp:textbox id=&quot;txtUserName&quot; runat=Server/> Visual Basic .NET <%@ Debug=true %> <script language=&quot;VB&quot; runat=&quot;server&quot;> Sub Page_Load(Sender As Object, E As EventArgs) txtUserName.Text = Request.Cookies(&quot;testing&quot;).Value.ToString End Sub <asp:textbox id=&quot;txtUserName&quot; runat=Server/> </li>  Save and view the .aspx page. The browser displays the error message that is referenced in the &quot;Symptoms&quot; section of this article, and the following line of code as the source of the problem: txtUserName.Text = Request.Cookies(&quot;testing&quot;).Value.ToString </li></ol>

<div class="references_section">