Cookies Explained in ASP.NET

Introduction

In this blog, I will explain cookies in ASP.Net. Cookies are one form of client-side state management. A cookie is often used to store user preferences or other information. It may contain the username, password or other information. Cookies are a small amount of text information stored on the client's browser and they don't use server memory. Cookies are stored limited to simple data only. One can configure cookies to expire when the browser session closes.

Example:

WebForm1.aspx.cs

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3. if (!IsPostBack)  
  4. {  
  5. if (Response.Cookies["UserName"] != null && Response.Cookies["Password"] != null)  
  6. {  
  7. txtUserName.Text = Response.Cookies["UserName"].Value;  
  8. txtPassword.Text = Response.Cookies["Password"].Value;  
  9. }  
  10. }  
  11. }  
  12.   
  13. protected void BtnSave_Click(object sender, EventArgs e)  
  14. {  
  15. Response.Cookies["UserName"].Value = txtUserName.Text;  
  16. Response.Cookies["Password"].Value = txtPassword.Text;  
  17. Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);  
  18. Response.Cookies["Password"].Expires = DateTime.Now.AddDays(1);  
  19. txtUserName.Text = "";  
  20. txtPassword.Text = "";  
  21.   
  22.   
  23. }  

Advantages:

1. Cookies are easy to implement.
2. The cookies are stored on the client's browser.
3. Cookies make browsing the internet easier and faster.
4. Cookies don’t require server resources they are stored on the client.

Disadvantages:

1. Users can delete the cookies.
2. The cookies are not secure, as they are stored in a clear text and no sensitive information should be stored in cookies.
3. User's browsers can refuse cookies.
4. Cookies can’t store complex information.