What is a Cookie ?
A Cookie is an object is used to store the sort amount of data onto client end. It executes on server and resides on client browser.
How does Cookie work ?
when users request a page from your site, your application sends not just a page, but a cookie containing some data. When the user’s browser gets the page, the browser also gets the cookie.Later, the user requests a page from your site again.If the cookie exists, the browser sends the cookie to your site along with the page
request.
What are different type of Cookie ?
How much can we store in a Cookie ?
Cookie specifications suggest that browsers should support a minimal number of cookies . In particular, an internet browser is expected to be able to store at least 300 cookies of four kilobytes each (both name and value count towards this 4 kilobyte limit), and at least 20 cookies per server or domain, so it is not a good idea to use a different cookie for each variable that has to be saved. It’s better to save all needed data into one single cookie.
|
Some Tips to implement Cookie :
1. How to Check User’s browser supports Cookie ?
HttpBrowserCapabilities browser;if (browser.Cookies)
{ bool isAllowCookie = true; } 2. How to get list of existing Cookies from User’s browser ? HttpBrowserCapabilities browser; if (browser.Cookies) 3. How to create a Session Cookie ? HttpBrowserCapabilities browser; if (browser.Cookies)
{ HttpCookie cookie = new HttpCookie(“SessionCookie”); context.Response.Cookies.Add(cookie); } Note : Session expire if browser is closed.
4. How to create a Persistent Cookie ? HttpBrowserCapabilities browser; if (browser.Cookies)
{ HttpCookie cookie = new HttpCookie(“Persistent Cookie”); cookie .Expires = DateTime.Now.AddMinutes(5); context.Response.Cookies.Add(cookie); } Note : Here only you have to provide cookie expire time.
5. How to add value to Cookie ?
HttpBrowserCapabilities browser;
if (browser.Cookies)
{ HttpCookie cookie = new HttpCookie(“SessionCookie”); cookie .Values.Add(“Name”, strUserName); cookie .Values.Add(“Password”, strPassword); context.Response.Cookies.Add(cookie); } 6. How to read values from cookie ?
HttpBrowserCapabilities browser;
HttpCookie cookie = Request.Cookies[“UserCookie”];
if (browser.Cookies)
{ if(cookie != null) { string strUserName = Request.Cookies(“UserCookie”)(“Name”).ToString(); string strPassword = Request.Cookies(“UserCookie”)(“Password”).ToString(); } } |