Read/write cookies in ASP.NET web pages using CookieCollections

Cookies are small pieces of data that are sent as part of the HTTP Response, get stored on the client machine, and then sent as part of any HTTP Request to the original web site. Cookies can be used to manage the state of a web page storing preferences, user information, etc.

With ASP.NET, a web page gets a Request.Cookies CookieCollection as a property of an HttpRequest object and returns a Response.Cookies CookieCollection of updates as a property of the HttpResponse object.

Cookies have a number of properties such as their name, value and expiry date. Cookies expire after a specified period of time. Once expired, the browser no longer sends it to the server. Thus, the Expires property of the cookie must always be in the future. To make a cookie permanent, set it to expire in, say 30 years.

Conversly, to delete a cookie, set it to expire at a point in the past. Never set it to expire immediately by using the current date/time since the server's time may be different than the client's time. Also, the Response.Cookies.Remove("TheCookie") method doesn't delete the cookie. It simply tells the cookie not to overwrite the client's cookie.

Incoming ASP.NET web pages have a CookieCollection inside the Request which lists all the cookies in this namespace on the client machine. If you try to access a coookie that doesn't exist in the Request, it will be null (or Nothing) so you must always test a cookie's existance.

On the Response side, no cookies exist when your code starts. Cookies get created as you access them. When the web server sends back the Response, the client machine only adjusts the Cookies that exist in the Response.Cookies collection. All others are left alone.

Here is the gotcha. Incoming request and outgoing response cookies are both from the HttpCookie class in .NET. Accessing a cookie that doesn't exist in the Response.Cookies collection, creates it with an empty string for the Value and an Expires date of 01-Jan-0001 00:00 meaning it expires immediately! Thus, looking at a cookie in the Response, either in code or even in the .NET IDE/debugger, overwrites the cookie on the client machine with an empty cookie that will expire as soon as the browser is closed!

Bottom line, your .NET code which updates cookies must start by copying the Request Cookie to the Response Cookie and then do all updates on the Response cookie.

Sample VB.NET code to update a cookie

    Private Sub Page_Load(......)
        '
        ' If the request cookie exists, copy it to the response.
        ' Otherwise create a response cookie.
        '
        If Request.Cookies("theCookie") Is Nothing Then
            Response.Cookies.Set(New HttpCookie("theCookie", "SomeValue"))
        Else 
            Response.Cookies.Set(Request.Cookies("theCookie"))
        End If
        '
        ' Add the expiration date. 
        '
        Response.Cookies("theCookie").Expires = DateTime.Now.AddYears(30)
        '
        ' Change the cookie's value 
        '
        If ... Then
            Response.Cookies("theCookie").Value = "NewValue"
        End If
        ...
    End Sub 

    Private Sub Button_OnClick(...)
        ...
        '
        ' Response.Cookies always has the latest values
        '
        If Request.Browser.Cookies Then
            currentCookieValue = Response.Cookies("theCookie").Value
        End If
        ...
    End Sub 


About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page