Explain cookies with example.

Answer

A cookie is a small amount of data that server creates on the client. When a web server creates a cookie, an additional HTTP header is sent to the browser when a page is served to the browser. The HTTP header looks like this:

Set-Cookie: message=Hello. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a header that looks like this:

Cookie: message=Hello

Cookie is little bit of text information. You can store only string values when using a cookie. There are two types of cookies:

- Session cookies
- Persistent cookies.

A session cookie exists only in memory. If a user closes the web browser, the session cookie delete permanently.

A persistent cookie, on the other hand, can available for months or even years. When you create a persistent cookie, the cookie is stored permanently by the user’s browser on the user’s computer.

Creating cookie

protected void btnAdd_Click(object sender, EventArgs e)
{
    Response.Cookies[“message”].Value = txtMsgCookie.Text;
}

// Here txtMsgCookie is the ID of TextBox.
// cookie names are case sensitive. Cookie named message is different from setting a cookie named Message.

The above example creates a session cookie. The cookie disappears when you close your web browser. If you want to create a persistent cookie, then you need to specify an expiration date for the cookie.

Response.Cookies[“message”].Expires = DateTime.Now.AddYears(1);

Reading Cookies
void Page_Load()
{
if (Request.Cookies[“message”] != null)
lblCookieValue.Text = Request.Cookies[“message”].Value;
}
// Here lblCookieValue is the ID of Label Control.

All asp Questions

Ask your interview questions on asp

Write Your comment or Questions if you want the answers on asp from asp Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---