Cookie with ASP.NET (C#)

Here, I am providing some helpful code snippets to work with Cookie in ASP.NET. if you don’t have any idea on Cookie, please surf here. This will help to get good idea on Cookie.

This one shows how to set and save values in Cookie.


//Set Cookie
HttpCookie userCookie = new HttpCookie("UserInfo");
userCookie["userName"] = TextBox1.Text;
userCookie["userPassword"] = TextBox2.Text;
userCookie.Expires = DateTime.Now.AddDays(3);
Response.Cookies.Add(userCookie);


Those following two code snippets show how to retrieve values from Cookie.


//Retrieve from Cookie
if (Request.Cookies["UserInfo"] != null)
{
 TextBox1.Text = Server.HtmlEncode(Request.Cookies["UserInfo"]["userName"]);
 TextBox2.Text = Server.HtmlEncode(Request.Cookies["UserInfo"]["userPassword"]);
}


//Retrieve from Cookie (another approach)
if (Request.Cookies["UserInfo"] != null)
{
 HttpCookie userCookie = Request.Cookies["UserInfo"];
 TextBox1.Text = userCookie["userName"];
 TextBox2.Text = userCookie["userPassword"];
}


However, you can't directly remove or delete Cookie from Client Computer, you can set expiration date for the very next time. This works like kind of removing Cookie.


//Remove Cookie 
Response.Cookies["UserInfo"].Expires = DateTime.Now.AddDays(-1);

Thanks
A Rahim Khan

Advertisements
    • sunny
    • September 3rd, 2011

    good by providing for students.. its nice we are thankfull to you….(mercy people)

    • Sara
    • October 11th, 2011

    Thanks rahim, its very helpfull

    • Ankit Singh
    • January 12th, 2012

    This is one of the best articles so far I have read online. Just useful information. Very well presented. Thanks for sharing with us. Check out this link too…
    http://mindstick.com/Articles/c4e253f5-67dc-4211-8a1f-e29c17ce2943/?Cookies%20in%20ASP.NET

    Its also helped me lot!!

    Thanks Everyone!!

    • jayant
    • December 24th, 2012

    sir, while i use
    ://Remove Cookie
    Response.Cookies[“UserInfo”].Expires = DateTime.Now.AddDays(-1);
    it deletes cookie on button’s second click.
    why ? T.Q in advance.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: