Wisdom of Helios

All About Cookies in ASP.net

Leave a comment

State Management in ASP.net

State Management in APS.NET is managed by two ways:

Client-Side or Server-Side Client-Side:Cookies,HiddenFields,ViewState and Query Strings.

Serve-Side:Application,Session and Database.

What Is A Cookie

A cookie is a small text file sent to a web user’s computer by a website/webpage. A cookie can be used to identify that user to the website on their next visit. Common uses include remembering login data, user preferences, and providing favorites lists.It is essentially your identification card, and cannot be executed as code or deliver viruses. It is uniquely yours and can only be read by the server that gave it to you . Cookies purpose is to tell the server that you returned to that Web page.It may help you by saving your time.If you personalize pages, or register for products or services, a cookie helps Microsoft remember who you are.

How Does A Cookie Work

(This portion is copied from msdn.microsoft.com)

Imagine that when users request a page from your site, http://www.contoso.com, your application sends not just a page, but a cookie containing the date and time. When the user’s browser gets the page, the browser also gets the cookie, which it stores in a folder on the user’s hard disk.

Later, the user requests a page from your site again. When the user enters the URL http://www.contoso.com, the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user, check an expiration date, or perform any other useful function.

Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange the http://www.contoso.com cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user’s browser as well; the browser stores all the cookies separately.

How Much Can We Store In A Cookie

Cookie specifications suggest that browsers should support a minimal number of cookies or amount of memory for storing them. In particular, an internet browser is expected to be able to store at least 300 cookies of four kilobytes each (both name and value count towards this 4 kilobyte limit), and at least 20 cookies per server or domain, so it is not a good idea to use a different cookie for each variable that has to be saved. It’s better to save all needed data into one single cookie.

How to use it

Writing Cookies

The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

You can also set a cookie’s date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now.

Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

If you do not set the cookie’s expiration, the cookie is created but it is not stored on the user’s hard disk. Instead, the cookie is maintained as part of the user’s session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.

Reading from Cookies

When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class. The structure of the HttpRequest object is essentially the same as that of the HttpResponse object, so you can read cookies out of the HttpRequest object much the same way you wrote cookies into the HttpResponse object. The following code example shows two ways to get the value of a cookie named username and display its value in a Label control:

if(Request.Cookies["userName"] != null)
    Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
    HttpCookie aCookie = Request.Cookies["userName"];
    Label1.Text = Server.HtmlEncode(aCookie.Value);
}

Before trying to get the value of a cookie, you should make sure that the cookie exists; if the cookie does not exist, you will get a NullReferenceException exception. Notice also that the HtmlEncode method was called to encode the contents of a cookie before displaying it in the page. This makes certain that a malicious user has not added executable script into the cookie. For more about cookie security, see the “Cookies and Security” section.


Author: Munir

I'm good for nothing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s