Cookies in ASP.NET

In this article I will explain you about cookies in ASP.NET and how to use them.

What is a cookie?

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.

In simple term, cookie is a small text file sent by web server and saved by web browser on client machine.

Some point to understand cookies

It is a server side object.

Cookies are used in state management.

HttpCookie class is there for cookie by .NET

Class-> httpSessionState

SessionID is send to the client in the form of cookie by server if the request is generated for the first time.

Session Cookie

Name -> ASP.NET_SessionID

Value -> will be alphanumeric value.

Name and value will be sent to client as session cookie (which is stored in cookie header).

ASP.NET 2.0 it is also used for mobile development.

Session timeout is 20 minutes by default (it depends on sliding time request).

In mobile development each request is treated as new request.

Earlier to 2.0 session was maintained but 2.0 onwards we have to explicitly maintain session (so we can use web and mobile development).

If the browser doesn't support cookie or cookies are off in browser,
Cookie less session is maintained.

Cookies can only store string type of data.

You can only store 4kb (4096 bytes) of data in cookie.

When browser goes out of scope cookies are expired.

Cookies can be stored in persist and non persist manner. By default cookies are non persistent.

Persistent cookies are sorted on client browser.

Cookies data is not secured.

Cookies are identified on basis of there name.

Single and multiple value cookies (on basis of key).

Cookies are domain specific also.

IE support more than 100 cookies.

Cookies were introduced from Netscape browser.

You can set the expiration date of the cookie for some day in the future it will remain their until that day unless manually deleted by the user

I will explain you with the help of a program how to store cookies and how to retrieve the cookies.

Code for Default.aspx design page
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title>Untitled Page</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>      
  10.     <asp:Button ID="Button1" runat="server" Text="Store Cookies" OnClick="Button1_Click" />  
  11.     </div>  
  12.     </form>  
  13. </body>  
  14. </html> 

cookieDesign1.gif

Code for Default.aspx.cs page
  1. using System;  
  2. using System.Configuration;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.HtmlControls;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.WebControls.WebParts;  
  11. using System.Xml.Linq;  
  12.   
  13. public partial class _Default : System.Web.UI.Page  
  14. {  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.    
  18.     }  
  19.    
  20.     HttpCookie myCookie;  
  21.   
  22.     protected void Button1_Click(object sender, EventArgs e)  
  23.     {  
  24.         myCookie = new HttpCookie("test");  
  25.         myCookie.Values["name"] = "Puran Singh Mehra";  
  26.         myCookie.Values["age"] = "30+";  
  27.         myCookie.Values["Profession"] = "Software";  
  28.         myCookie.Values["Address"] = "India";  
  29.    
  30.         myCookie.Expires = DateTime.Now.AddHours(1);  
  31.         Response.Cookies.Add(myCookie);  
  32.         Response.Redirect("Default2.aspx");  
  33.     }  
  34. }  
Output 1:

cookieOutput1.gif

Code for Default2.aspx design page
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title>Untitled Page</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="top: 231px;  
  11.             left: 476px; position: absolute; height: 26px; width: 116px" Text="Show Cookie" />  
  12.     </div>  
  13.     </form>  
  14. </body>  
  15. </html> 

cookieDesign2.gif

Code for Default2.aspx.cs design page
  1. using System;  
  2. using System.Collections;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Security;  
  8. using System.Web.UI;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Web.UI.WebControls;  
  11. using System.Web.UI.WebControls.WebParts;  
  12. using System.Xml.Linq;  
  13.   
  14. public partial class Default2 : System.Web.UI.Page  
  15. {  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         foreach (string str in Request.Headers)  
  19.         {  
  20.             Response.Write(str + "=" + Request.Headers[str] + "<br>");  
  21.         }  
  22.         Response.Write("________________________________________________" + "<br>");  
  23.     }  
  24.   
  25.     protected void Button1_Click(object sender, EventArgs e)  
  26.     {  
  27.         foreach (string str in Request.Cookies["test"].Values)  
  28.         {  
  29.             Response.Write(str + "=" + Request.Cookies["test"].Values[str] + "<br>");  
  30.         }   
  31.     }  
  32. }  
Output 2:

cookieOutput2.gif
Output 3:

cookieOutput3.gif
Cookies Merits

Data is stored on client side, so it is faster. Cookies are best used to store small amounts of data, for example it can store User ID and Password. This UserID and Password can then be used to identify the user and read user information from a database or other data store. It is recommended to encrypt a password before it is stored in a cookie as cookies are not secured.

Cookies Demerits

Security problem as they are stored on client.
Client can delete cookie any time.
Browsers also impose limitations on how many cookies your site can store on the user's computer.
Cookie can only store 4kb of data.
Data is not authenticated i.e. client can delete the cookie.

Conclusion

I hope that this article would have helped you in understanding Cookies in ASP.NET. How you can use them to save state management. Please share it if you know more about this attribute. Your feedback and constructive contributions are welcome.
  
Read more >> Cookies in ASP.NET