Article posted by Sheonarayan
on 6/18/2011 | Views: 8298 | Category: ASP.NET
| Level: Advance | Points: 250
In this article, we are going to learn how to set the expiration date and time for the cookies created in ASP.NET.
A Cookie is a small amount of text that attached to the requet and response in between browser and the server. This small amount of text can be read by the application whenever user browse it. Please note that cookie is not a good medium to store the confidential data as it is stored into the user browser.
<p><asp:Label ID="lblTime" runat="server" EnableViewState="false" /></p>
<asp:Button ID="btnCookieSet" runat="server" Text="Set Cookie" OnClick="SetCookie" />
<asp:Button ID="btnCookieGet" runat="server" Text="Get Cookie" OnClick="GetCookie" />
In the above code snippet, we a Label and two buttons. Label is used to write the current date time on the page. The first button executes SetCookie server side method and second button executes GetCookie server side method.
protected void Page_Load(object sender, EventArgs e)
lblTime.Text = DateTime.Now.ToString();
protected void SetCookie(object sender, EventArgs e)
// set the cookie
Response.Cookies["MyCookie"].Value = "My cookie data";
Response.Cookies["MyCookie"].Expires = DateTime.Now.AddSeconds(10);
protected void GetCookie(object sender, EventArgs e)
if (Request.Cookies["MyCookie"] != null)
string cookieValue = Request.Cookies["MyCookie"].Value;
Get video tutorials of hundreds of ASP.NET Tips and Tricks.
In the SetCookie server side method, we are setting the cookie value and setting the Expiry date of the cookie by setting the Expires property. This will set the expiry date to current date time + 10 seconds, it means that this cookie should expire (the cookie should be deleted from the browser) in 10 seconds.
This method first checks for the “MyCookie”, if it is not null then get the cookie value using the Request object and writes on the page.
Hope this article was useful. Keep reading ... In the next article we shall learn how to read and write multi-valued cookies in ASP.NET.
Thanks for reading.
If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.
Found interesting? Add this to: