Cookies

What is ASP.NET Cookies?

In ASP.NET, cookies are small pieces of data that are stored on the client-side (i.e., in the user's web browser) and are sent between the client and the server with each HTTP request and response. Cookies are used to store user-specific information and preferences across multiple requests, enabling a stateful web experience in an otherwise stateless environment like the HTTP protocol.

Key Concepts of ASP.NET Cookies:

  • Client-Side Storage : Cookies are stored on the user's device, typically in the browser. This allows the server to retrieve user information (such as user preferences, authentication tokens, session data) on subsequent requests without needing to re-enter or recalculate the information.
  • Data Persistence : Cookies can persist across multiple sessions (if specified), meaning they can be used to remember a user's preferences, login state, and other details even after the user has closed their browser and later reopened it. They can also be set to expire after a certain period or when the session ends.
  • HTTP Headers : Cookies are stored as part of the HTTP headers. When a user sends a request to the server, cookies are included in the request headers. Similarly, when the server sends a response, cookies are set in the response headers, which the browser stores for future requests.
  • Key-Value Pairs : A cookie contains a name (key) and a value. For example, a cookie might be used to store a "username" or "theme preference" for the user.
  • Security : Cookies can be encrypted and marked as secure to ensure sensitive information is protected. Secure cookies are only transmitted over HTTPS, and cookies can also be marked as HttpOnly to prevent JavaScript from accessing them (thus enhancing security against cross-site scripting attacks).

Cookies Code Examples


    protected void btncreate_Click(object sender, EventArgs e)
    {
       Response.Cookies["name"].Value = txtcreatecookie.Text;
       Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(1);
       Label1.Text = "Cookie Created";
       txtcreatecookie.Text = "";
    }    
    protected void btnretrieve_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["name"] == null)
        {
            txtretrieve.Text = "No cookie found";
        }
        else
        {
            txtretrieve.Text = Request.Cookies["name"].Value;
        }
    }                                 
      

Output Example

Cookie Created

we create cookie with name parameter and assign textbox values to name cookie.

Cookie Retrived

Set the expiration time to 1 minute, after which the cookie will be deleted, and a 'No cookie found' message will be displayed.