How to read cookies in ASP.NET?

Sheonarayan
Posted by in ASP.NET category on for Advance level | Points: 250 | Views : 41259 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to learn how to read cookies in different ways using 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 the 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

<asp:Button ID="btnCreate" runat="server" Text="Read Cookie - One way" OnClick="ReadCookie1" />

<asp:Button ID="Button1" runat="server" Text="ReadCookie - Other way" OnClick="ReadCookie2" />

In the above code snippet, we have two buttons. The first button executes ReadCookie1 method and second button executes ReadCookie2 method.

CODE BEHIND

protected void ReadCookie1(object sender, EventArgs e)

{

HttpCookie cookie = Request.Cookies["CookieKey1"];

Response.Write(cookie.Value);

}


protected void ReadCookie2(object sender, EventArgs e)

{

Response.Write(Request.Cookies["CookieKey2"].Value);

}

 

Get hundreds of ASP.NET How to Tips and Tricks.

ReadCookie1 method

In this method, we are retrieving the cookie using Request object and saving into HttpCookie variable. The next line writes the cookie value on the page.

ReadCookie2 method

In this method, we are retrieving the cookie value using Request.Cookies collection by passing the Cookiename as parameter.

OUTPUT


In this article, we learnt how to read the cookies. To know how to set the expiration date time of the cookies, click here.

To learn how to create cookies in ASP.NET, click here.

Thanks. If you like this article, share it to your friends by tweeting or sharing it via facebook, linkedin or other websites.

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Naimishforu on: 6/22/2011 | Points: 25
Nice article! Thanks, it had helped much.
Posted by: Lakn2 on: 6/29/2011 | Points: 25
good one
Posted by: Niranjan44 on: 1/9/2013 | Points: 25
You can also find here in simple way

http://www.programcall.com/6/dotnet/cookie-in-.net.aspx

Login to post response

Comment using Facebook(Author doesn't get notification)