## Contents

Contents

### The short explanation, if you don’t like to read the entire story

If you use code like if (Response.Cookies["mycookie"] != null) { … }, ASP.Net automatically generates a new cookie with the name “mycookie” in the background and overwrites your old cookie! Always use the Request.Cookies-Collection to read cookies!

### The long explanation and some useful advices at the end

You can access the Cookies-Collection in two different places in ASP.Net:

To make your life easier (or harder, as you will see later), ASP.Net gives you the possibility to add a cookie to the browser this way:

 1 2  Response.Cookies["mycookie"].Value = "some value"; Response.Cookies["mycookie"].Expires = DateTime.Now.AddDays(10); 

As you can see here, the .NET framework automatically generates the HttpCookie instance with the name “mycookie” in the background and adds it to the collection.

Sending cookies to the browser this way is perfectly fine.

The important thing you have to know when reading cookies is, that the Response.Cookies collection is empty at the beginning of every request. The cookie with the name “mycookie” can only be found in the Request.Cookies-Collection!

 1 2 3 4  if (Response.Cookies["mycookie"] != null) { // This automatically overwrites the existing cookie with an empty value!!! } 

 1 2 3 4  if (Request.Cookies["mycookie"] != null) { // This is fine }