Cookie: a cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.
Common use of cookies is to remember users between visits. You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Create a cookie in ASP.NET:The System.Web namespace offers a class called HttpCookie to create cookies.
// Use this line when you want to save a cookie
Response.Cookies["MyCookieName"].Value = "MyCookieValue";
// How long will cookie exist on client hard disk
Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);
// To add multiple key/value pairs in single cookie
Response.Cookies["VisitorData"]["FirstName"] = "Richard";
Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();
Read a cookie in ASP.NET:
string MyCookieValue;
// We need to perform this check first, to avoid null exception
// if cookie not exists
if(Request.Cookies["MyCookieName"] != null)
MyCookieValue = Request.Cookies["MyCookieName"].Value;
Delete cookie in ASP.NET:To delete existing cookie we actually just set its expiration time to some time in the past. You can do it with code like this:
// First check if cookie exists
if (Request.Cookies["MyCookieName"] != null)
{//Set its expiration time somewhere in the past
Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(-1);
}
No comments:
Post a Comment