Hi,
In my last post I wrote about and overview of cookie, there basic use and some of their limitation. In this post I will talk on how do we read and write cookies with the help of Asp.Net.
When a browser makes a request to the server it also send existing (at the browser end) cookies information for that website. In Asp.Net the HttpRequest (also referred as Request property in the page class) objects contains a collection of all the cookies sent by the browser.
We can read the cookies from the request object like this.
if (Request.Cookies["lastVisit"] != null)
string strlastVisit = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
W should always check if the cookie exists or not before working with cookie. Because as mentioned in my last article the browser may not contain those cookies for many reason.
To write a new cookie to the browser we use the HttpResponse (also referred as Response property in the page class) Object. To add a new cookie we add a new cookie in the cookie collection of the response object. We can either create a new object of HttpCookie or directly add the cookie to the response object. Here is the code of the same
Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(30);
OR
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires= DateTime.Now.AddDays(30);
Response.Cookies.Add(aCookie);
Both of the above code does the same work. They add a cookie to the response collection, which in turn will add the cookie in the browser if the browser supports them. In the above code we also add an expiry date for the cookie. The cookie will be used for next 30 days only after which it will expire and not be used. Note that the expiry date for a cookie is set only. The browser never sends the information of when will the cookie be expiring
This does the work for basic working with cookie in Asp.Net. In the next post I will talk about some of the more feature that are available with cookie in Asp.Net
Vikram