ASP.NET Cookies Overview
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. The cookie contains information the Web application can read whenever the user visits the site.
Scenarios when we use cookie
In Web applications we can use Cookies to store user-specific information. For example, when a user visits your site, you can use cookie to store user preferences or login information. When the user visits your Web site next time, the application can retrieve the information it stored earlier in cookie.
How Cookies work in Background
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.
For example, if any user requests a page from your site and your application send a cookie with page that containing the user login information, when the user browser gets the page, the browser also gets the cookie, which it stores in a folder on the user hard disk.
next time when that user requests a page from your site again, when the user enters the URL then browser looks on the local hard disk for a cookie associated with that URL. If browser find any cookie, the browser sends the cookie to your site with the page request. Your application can then get the user login information. You might use the information.
All Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site.
Limitations of Cookie
cookies can store information up to 4096 bytes(4 kb). Because of this small limit, cookies are best used to store small amounts of data. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.
Writing Cookies
It is browser responsibility to manage cookies on a user system. Cookies are sent to the browser which request the url via the HttpResponse object that have a collection called Cookies.we can access the HttpResponse object as the Response property of your Page class. When creating a cookie, you must specify a Name and Value. every cookie must have a unique name it will help you to identified later when reading it from the browser.
You can also set expiration date and time for a cookie.The cookies that are expired will be deleted by the browser when a user visits the site that wrote the cookies.
Note:A users can clear the cookies on their computer at any time. Even if cookies has long expiration times.If you have not set the cookie's expiration,then the cookie will be deleted when user close the browser.
In the following example i am showing two methods to write cookies:
Response.Cookies["MyName"].Value = "Shanti";
Response.Cookies["MyName"].Expires = DateTime.Now.AddDays(10);
HttpCookie MyCookie = new HttpCookie("YourName");
MyCookie.Value = "Rajesh";
MyCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(MyCookie);
The above example adds two cookies to the Cookies collection, one named MyName and the other named YourName.
Writing Cookies having More Than One Value
we can store multiple name-value pairs in a single cookie. The name-value pairs are referred to as subkeys.by writing this type of cookie we can put related infomation in a single cookie.A cookie that contains subkeys also helps you limit the size of cookie files. because cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site.
Response.Cookies["AllName"]["Myname"] = "Shanti";
Response.Cookies["AllName"]["Yourname"] = "Rajesh";
Response.Cookies["AllName"].Expires = DateTime.Now.AddDays(10);
HttpCookie aCookie = new HttpCookie("AllName");
aCookie.Values["Myname"] = "Shanti";
aCookie.Values["yourname"] = "Rajesh";
aCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(AllName);
Reading a Cookies
we can read the cookies using the HttpRequest object.
if (Request.Cookies["Myname"] != null)
lbmyname.text = "My name is " + Request.Cookies["Myname"].Value + "!";
if (Request.Cookies["Yourname"] != null)
lbYourname.text = "Your name is " + Request.Cookies["Yourname"].Value + "!";
Advantages:
Simplicity
Disadvantages:
Cookies can be disabled on user browsers .
Cookies are transmitted for each HTTP request/response causing overhead on bandwidth .
Inappropriate for sensitive data.
State Management in ASP.NET
This article discusses various options for state management for web applications developed using ASP.NET. web applications are based on stateless HTTP protocol which does not maintain any information about user requests. In client and server communication using HTTP protocol,the web page is created each time the page is requested.
Developer is forced to implement various state management techniques when developing applications which provide customized content and which maintain the different user info.
I will show here various options for ASP.NET developer to implement state management techniques in their applications.
state management techniques are two types.
1- client side state management
2- server side state management
Client side state management
In ASP.Net there are four ways to manage client side state. What does that mean client side state management? When your user clicks on an URL or button or server side control, the information goes from your page to the server and then back again to the users web browser. How do you remember the information that is currently on the page. These are the techniques to save the information on the client side and not the server side.
The five methods of client side state management are:
- Query String
- Cookies
- Hidden Fields
- View State
- Control state (ASP.NET 2.0).
While implementing client side state management they involve in each roundtrip to server so Bandwidth should be considered. for example Cookies are exchanged between client and server for each page request.
View State
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. View state is the default method that the asp.net page uses to preserve page and control property values between round trips to clients and servers.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page. The information can be stored in multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property.
Control State
Various time we need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. We can use ViewState property for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control.To solve this problem, the ASP.NET page framework exposes a feature called control state.
Hidden Fields
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page.
Note :It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page.
In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available.
Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. Usually, information is stored as name-value pairs. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information.
- Note : Cookies can be disabled on user browsers and Cookies are transmitted for each HTTP request/response causing overhead on bandwidth.
Query Strings
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text.
Query strings looks like this
http://www.tectopix.blogspot.com/booksdetails.aspx?bookcategory=basic&bookprice=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "bookcategory" and the other called "bookprice."
Query strings provide a simple but limited way to maintain state information. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
Note :Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data.
Server side state management
Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large.
The following are the server-side state management options in ASP.NET
1-Application state
2-Profile properties
3-Database support
4-Session state
Application State
ASP.NET allows us to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.
ASP.NET provides three events that enable you to initialize Application variables.
Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.
Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.
Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.
Advantages of using application state are:
Application state is easy to use.
Because application state is accessible to all pages in an application, so it has only a single copy of the information.
Session State
ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.
Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner. For more information, see ASP.NET Profile Properties Overview.
Database Support
In some cases, you might want to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state information by using a relational database for the following reasons:
