ASP.NET Cookies
From JholJhapata
Cookies is a small piece of information stored on the client machine. Its is used to store user preference information like Password, City, SessionId etc on client machines. We need to import namespace called Systen.Web before we use cookie(HttpCookie).
Contents
Type of Cookies
- Persistent Cookie - Persistent cookies are permanent cookies.They are stored as a text file in the hard disk of the computer.
- Non-Persistent Cookie - These cookies are also known as temporary cookies or session based cookies.They are active as long as the browser remains active. Once the browser is closed the cookies vanishes automatically.
Create a cookie
In the Asp.Net with help of Response object or HttpCookie we can create a cookie.
Example 1
HttpCookie info = new HttpCookie("info"); info["UserFirstName"] = "Soumya"; info["UserLastName"] = "Das"; info.Expires.Add(new TimeSpan(0, 1, 0)); Response.Cookies.Add(info);
Example 2
Response.Cookies["UserFirstName"].Value = "Annathurai"; Response.Cookies["UserLastName"].Value = "Black";
Retrieve value from cookie
In the Asp.Net with help of Response object or HttpCookie we can retrieve cookies.
Example 1
string UserFirstName = Request.Cookies["UserFirstName"].Value; string UserLastName = Request.Cookies["UserLastName"].Value;
Example 2
HttpCookie reqCookies = Request.Cookies["userInfo"]; if (reqCookies != null) { string UserFirstName = reqCookies["UserFirstName"].ToString(); string UserLastName = reqCookies["UserLastName"].ToString(); }
Cookie's property
Property | Description |
---|---|
Domain | Which is used to associate cookies to domain. |
Secure | We can enable secure cookie to set true(HTTPs). |
Value | We can manipulate individual cookie. |
Values | We can manipulate cookies with key/value pair. |
Expires | Which is used to set expire date for the cookies. |
Advantages of Cookie
- Its clear text so user can able to read it.
- We can store user preference information on the client machine.
- Its easy way to maintain.
- Fast accessing.
Disadvantages of Cookie
- If user clear cookie information we can't get it back.
- No security.
- Each request will have cookie information with page.