Cookies in ASP.NET - C# Tutorials

 Cookies in ASP.NET - C# Tutorials

 Type of Cookies

  1. Persist Cookie - A cookie has not have expired time Which is called as Persist Cookie
  2. Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?

 
It is really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
 
Example 1

    HttpCookie CookiesName= new HttpCookie("CookiesName");

    CookiesName.Expires = DateTime.Now.AddDays(1);

    CookiesName["SessionID"] = Session["SessionID"].ToString();

    Response.Cookies.Add(CookiesName);

 

Example 2
 
    HttpCookie CookiesName= new HttpCookie("CookiesName");

    CookiesName.Expires = DateTime.Now.AddDays(1);

    Response.Cookies.["userName"].Value="Annathurai"

       Response.Cookies.["userColor"].Value="Black"

    Response.Cookies.Add(CookiesName);

;  

How to retrieve from cookie?

 
It is easy way to retrieve cookie value form cookies with the help of Request object.
 
Example 1
  1. string User_Name = string.Empty;  
  2. string User_Color = string.Empty;  
  3. User_Name = Request.Cookies["userName"].Value;  
  4. User_Color = Request.Cookies["userColor"].Value;  
Example 2
  1. string User_name = string.Empty;  
  2. string User_color = string.Empty;  
  3. HttpCookie reqCookies = Request.Cookies["userInfo"];  
  4. if (reqCookies != null)  
  5. {  
  6.     User_name = reqCookies["UserName"].ToString();  
  7.     User_color = reqCookies["UserColor"].ToString();  
  8. }  
When we make a request from the client to web server, the web server process the request and give a lot of information with big pockets which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.
 

Cookie's common property

  1. Domain => Which is used to associate cookies to domain.
  2. Secure  => We can enable secure cookie to set true(HTTPs).
  3. Value    => We can manipulate individual cookie.
  4. Values  => We can manipulate cookies with key/value pair.
  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie

  1. Its clear text so user can able to read it.
  2. We can store user preference information on the client machine.
  3. Its easy way to maintain.
  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can't get it back.
  2. No security.
  3. Each request will have cookie information with page.

How to clear the cookie information?

  1. We can clear cookie information from client machine on cookie folder
  2. To set expires to cookie object
    1. userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.

 

Follow for more updates and comment your suggestions 

 

 

 

 

 

Post a Comment

0 Comments

Translate

Close Menu