Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 9802 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to set the expiration datetime for the cookies in ASP.NET?

How to set the expiration datetime for the cookies in ASP.NET?

1 vote(s)
Rating: 5 out of 5
Article posted by Sheonarayan on 6/18/2011 | Views: 8298 | Category: ASP.NET | Level: Advance | Points: 250 red flag

Advertisements

Advertisements
In this article, we are going to learn how to set the expiration date and time for the cookies created in ASP.NET.


Introduction

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.


ASPX PAGE

<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.

CODE BEHIND

 

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;

Response.Write(cookieValue);

}

}

Get video tutorials of hundreds of ASP.NET Tips and Tricks.

SetCookie method

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.

GetCookie method

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.

OUTPUT

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.

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Akiii | Posted on: 21 Jun 2011 12:08:29 AM | Points: 25

Hi sir,
I am using this code below:-
Response.Cookies["MyCookie"].Value = "My cookie data";

Response.Cookies["MyCookie"].Expires = DateTime.Today;
string Value = Request.Cookies["MyCookie"].Value;
Response.Write(Value);


I want that my cookie should be valid throughout the day. But after some seconds if i click the getcookie method then value is gone.....!
Can you please explain, what i am doing wrong ?

Thanks and Regards
Akiii

Posted by: SheoNarayan | Posted on: 21 Jun 2011 12:16:34 AM | Points: 25

Set the Expires property of the Cookies to more than today. So you can write something like

Response.Cookies["MyCookie"].Expires = DateTime.Now.AddDays(1);


and it should work.

Thanks

Posted by: Akiii | Posted on: 21 Jun 2011 10:48:02 AM | Points: 25

yes sir it working....

thanks for the help..
Akiii

Posted by: SheoNarayan | Posted on: 21 Jun 2011 11:16:58 AM | Points: 25

Great, happy to hear this.

Thanks

>> Write Response - Respond to this post and get points
Related Posts

In this artcle , I will be explaining the common and mostly used web.config tags, their different sections and also dicuss about securing the the config file.

We must have came across a situation where we have to call methods of different classes under same transaction scope and rollback the operations if any error occurs during execution of any methods. For eg. If we have Debit and Credit class and DebitAmount method of Debit class executed successfully but an error occurred while calling CreditAmount method of Credit class, we should be able to rollback all operations done by DebitAmount method. In scenario like this we can use System.Transactions.TransactionScope to rollback all operations done by DebitAmount method.

After Selecting the row or checking the multiple row in a Gridview you can delete the data in just one click.

On November 19, 2007, Microsoft officially released the ASP.NET version 3.5 and Visual Studio 2008. Like with the progression from ASP.NET 2.0 to 3.0, the features in ASP.NET 3.5 are additive, meaning that the core assemblies installed from the .NET Framework version 2.0 are still used by the 3.0 and 3.5 versions. The In short, ASP.NET 3.5 doesn't change or take away or break any functionality, concepts, or code present in 2.0 - it simply adds new types and features and capabilities to the framework.

In this example i'll show how to detect the session timeout which occurs when user is idle for the time specified as Session.Timeout,using C# asp.NET and if it is than redirect the user to login page to login again, for this i've set time out value in web.config file to 1 minute

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/18/2013 1:05:47 AM