An Overview Of Cookies In ASP.NET

Introduction

 
In this article, I'll explain cookies in Asp.Net  and how to use cookies in C# and VB.Net with an appropriate example. A way to use Browser Cookies in ASP.Net is reading values and keeping it in Cookies, writing (saving) values in Cookies and additionally, a way to delete/remove/clear Cookies in ASP.Net using C# and VB.Net.
 

What is Cookie in ASP.Net?

 
A cookie could be a tiny little bit of text that accompanies requests and pages as they're going between the online server and browser. The cookie contains data the online application will scan whenever the user visits a website.
 
For example, if a user requests a page from your website and your application sends not simply a page, however additionally a cookie containing the date and time, once the user's browser gets the page, the browser additionally gets the cookie, that it stores in an exceeding folder on the user's magnetic disk.
 
Later, if user requests a page from your website once more, when the user enters the universal resource locator (URL)  the browser appearance on the native magnetic disc for a cookie related to the universal resource locator (URL). If the cookie exists, the browser sends the cookie to your website together with the page request. Your application will then confirm the date and time that the user last visited the positioning.  you may use the data to show a message to the user or check expiration date.
 
Cookies are related to an internet website, not with a particular page, therefore the browser and server can exchange cookie data despite what page the user requests from your website. because the user visits completely different sites, every website would possibly send a cookie to the user's browser as well; the browser stores all the cookies on an individual basis.
 

How to Read, Write and Clear Cookies in ASP.Net?

 
The following markup language consists of associate ASP.Net TextBox and 3 ASP.Net Buttons for Writing, Reading and Deleting browser cookies.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7.     <style type="text/css">  
  8.         body  
  9.         {  
  10.             font-family: Arial;  
  11.             font-size: 10pt;  
  12.         }  
  13.         .button {  
  14.     background-color: #ff6a00; /* Green */  
  15.     border: none;  
  16.     color: white;  
  17.     padding: 15px 32px;  
  18.     text-align: center;  
  19.     text-decoration: none;  
  20.     display: inline-block;  
  21.     font-size: 16px;  
  22. }  
  23.         input[type=text] {  
  24.     border: none;  
  25.     width :33.5%;  
  26.     height:35px;  
  27.      font-size: 16px;  
  28.     border-bottom: 2px solid #0072ff;  
  29. }  
  30.     </style>  
  31. </head>  
  32. <body>  
  33.     <form id="form1" runat="server">  
  34.     <b> Name:</b>  
  35.     <asp:TextBox ID="txtName" runat="server" />  
  36.     <br />  
  37.     <br />  
  38.     <asp:Button ID="btnWrite" CssClass="button" Text="Write Cookie" runat="server" OnClick="WriteCookie" />  
  39.     <asp:Button ID="btnRead" CssClass="button" Text="Read Cookie" runat="server" OnClick="ReadCookie" />  
  40.     <asp:Button ID="btnDelete" CssClass="button" Text="Remove Cookie" runat="server" OnClick="RemoveCookie" />  
  41.     </form>  
  42. </body>  
  43. </html>  

How to Write Cookies in ASP.Net?

 
When the Write Cookie Button is clicked, the individual Button click event handler is executed that saves the worth of the Name TextBox to the Browser Cookie using the item of the HttpCookie category.
 
Finally the Cookie is added to the Response.Cookies assortment.
 
Write following code in click event of button WriteCookie.
 
C# Code
  1. protected void WriteCookie(object sender, EventArgs e)  
  2.   {  
  3.       //Create a Cookie with a suitable Key.  
  4.       HttpCookie nameCookie = new HttpCookie("Name");  
  5.   
  6.       //Set the Cookie value.  
  7.       nameCookie.Values["Name"] = txtName.Text;  
  8.   
  9.       //Set the Expiry date.  
  10.       nameCookie.Expires = DateTime.Now.AddDays(30);  
  11.   
  12.       //Add the Cookie to Browser.  
  13.       Response.Cookies.Add(nameCookie);  
  14.   }  
Vb.Net Code
  1. Protected Sub WriteCookie(sender As Object, e As EventArgs)  
  2.         'Create a Cookie with a suitable Key.  
  3.         Dim nameCookie As New HttpCookie("Name")  
  4.   
  5.         'Set the Cookie value.  
  6.         nameCookie.Values("Name") = txtName.Text  
  7.   
  8.         'Set the Expiry date.  
  9.         nameCookie.Expires = DateTime.Now.AddDays(30)  
  10.   
  11.         'Add the Cookie to Browser.  
  12.         Response.Cookies.Add(nameCookie)  
  13.     End Sub  

How to Read Cookies in ASP.Net?

 
When you will click on read Cookie Button,  the several Button event handler fetches the HttpCookie object from the Request.Cookies assortment using its Key.
 
The value read from the Cookie is displayed using JavaScript Alert Box.
 
Write the following code in click event of button ReadCookie.
 
C# Code
  1. protected void ReadCookie(object sender, EventArgs e)  
  2.     {  
  3.         //Fetch the Cookie using its Key.  
  4.         HttpCookie nameCookie = Request.Cookies["Name"];  
  5.   
  6.         //If Cookie exists fetch its value.  
  7.         string name = nameCookie != null ? nameCookie.Value.Split('=')[1] : "undefined";  
  8.         ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('" + name + "');"true);  
  9.     }  
VB.Net  Code
  1. Protected Sub ReadCookie(sender As Object, e As EventArgs)  
  2.       'Fetch the Cookie using its Key.  
  3.       Dim nameCookie As HttpCookie = Request.Cookies("Name")  
  4.   
  5.       'If Cookie exists fetch its value.  
  6.       Dim name As String = If(nameCookie IsNot Nothing, nameCookie.Value.Split("="c)(1), "undefined")  
  7.       ClientScript.RegisterStartupScript(Me.[GetType](), "alert", (Convert.ToString("alert('") & name) + "');"True)  
  8.   End Sub  

How to Clear Cookies in ASP.Net?

 
When the remove Cookie Button is clicked, the individual Button event handler fetches the Cookie object from the Request.Cookies assortment using its Key.
 
A Cookie can't be removed or deleted, it solely is created invalid and therefore the expiration Date of the Cookie is about a past date and therefore the Cookie is updated back to the Response.Cookies assortment.
 
Write the following code in click event of button RemoveCookie.
 
C# Code
  1. protected void RemoveCookie(object sender, EventArgs e)  
  2.   {  
  3.       //Fetch the Cookie using its Key.  
  4.       HttpCookie nameCookie = Request.Cookies["Name"];  
  5.   
  6.       //Set the Expiry date to past date.  
  7.       nameCookie.Expires = DateTime.Now.AddDays(-1);  
  8.   
  9.       //Update the Cookie in Browser.  
  10.       Response.Cookies.Add(nameCookie);  
  11.   }  
Vb.Net Code
  1. Protected Sub RemoveCookie(sender As Object, e As EventArgs)  
  2.         'Fetch the Cookie using its Key.  
  3.         Dim nameCookie As HttpCookie = Request.Cookies("Name")  
  4.   
  5.         'Set the Expiry date to past date.  
  6.         nameCookie.Expires = DateTime.Now.AddDays(-1)  
  7.   
  8.         'Update the Cookie in Browser.  
  9.         Response.Cookies.Add(nameCookie)  
  10.     End Sub  
Output Screen
 
Screen For Writing Cookie
Screen For Write Cookie 
Screen For Reading Cookie
Screen For Write Cookie 
Finally, Remove Cookie will remove the Cookie from your web browser.


Similar Articles
Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.