Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store string in a cookie and retrieve it

I want to store the username in the cookie and retrieve it the next time when the user opens the website. Is it possible to create a cookie which doesnt expires when the browser is closed. I am using asp.net c# to create the website. And how can I stop the browser from offering to save username and password

like image 534
Murthy Avatar asked Dec 13 '11 11:12

Murthy


People also ask

Can Cookies store string data?

Data of any type you can serialize into a string and deserialize back into that type can be stored in a cookie. For instance: Object , DateTime , Int , Decimal , etc. It entirely depends on your coding logic; string can be converted back to anything almost, Object.

How much text can you store in a cookie?

So, what are cookies? According to whatarecookies.com, they are small text files that are placed on a user's computer by a website. They hold a very small amount of data at a maximum capacity of 4KB.

How do I store multiple values in cookies?

To store multiple key-value pairs in a cookie, you have to create a custom object, convert it to a JSON string with the help of the “stringify()” method, and store the resultant “document. cookie” object.


1 Answers

Writing a cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");

Reading a cookie

HttpCookie myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");
like image 145
Shai Avatar answered Nov 15 '22 14:11

Shai