Friday, 13 February 2015

Cookie Management in ASP.NET


Cookie Management 

  • A set of Cookies is a small text file that is stored in the user's hard drive using the client's browser.
  •  Cookies are just used for the sake of the user's identity matching as it only stores information such as sessions id's, some frequent navigation or post-back request objects.
  • Whenever we get connected to the internet for accessing a specific service, the cookie file is accessed from our hard drive via our browser for identifying the user.
  •  The cookie access depends upon the life cycle or expiration of that specific cookie file.

Data is always stored as name-value pairs

To read a cookie you use the Request.Cookies method. You must always ensure that the cookie is not null before you use it.
Point 1: Write into a cookie collection:
Response.Cookies.Add(new HttpCookie(“cookiedata”, “This is some data stored in the cookie”));
Point 2: Reading cookie data
String readdata;
If(Request.Cookie[“cookiedata”] != null)
{
Readdata=Server.HtmlEncode(Request.Cookie[“cookiedata”].Value);
}
You can also set an expiration for the cookie using the Expires property.
Point 3: Setting cookie expiry
Response.Cookies[“cookiedata”].Expires=DateTime.Now.AddDays(1);
Here the cookie is allowed to expire after a day.
You can also control the scope of your cookie so that applications or pages outside the scope do not have access to your cookie.
Point 4: Setting cookie scope
Response.Cookies[“cookiedata”].Path=”/MyApp”;
Here the scope of the cookie is set to a “MyApp” virtual directory. Pages outside of this cannot access the cookie.
You can also to set the cookie scope to a domain.
Point 5: Setting a domain as cookie scope
Response.Cookies[“cookiedata”].Domain=”remalamanoj.com”;
You can also store multiple values in a cookie. Multiple values are stored as multiple key-values in a single cookie.
Point 6: Cookies with multiple values
Response.Cookies[“cookiedata”][“name”]=”Mr.MANOJ”;
Response.Cookies[“cookiedata”][“lastvisit”]=DateTime.Now;


Points to Remember Some features of cookies are:
  • Store information temporarily
  • It's just a simple small sized text file
  • Can be changed depending on requirements
  • User Preferred
  • Requires only a few bytes or KBs of space for creating cookies

No comments:

Post a Comment