Cookies in asp .net

In this asp .net tutorial we will learn how to use cookies. Cookies are small text files that we can store and retrieve from user’s computer. We use cookies to Set and Get user specific values from our website.Most browsers support cookies of up to 4096 bytes. 
 
Cookies are really helpful when we need to store small amount of text information from our website for later use. E.g. We can store and retrieve theme selected by our user. Although cookies are very easy to use but it is recommended to avoid cookies to store any sensitive data like passwords, bank accounts etc. because cookies are sent between browser and server as plain text and can be easily read and tampered. There are options available to Encrypt and Decrypt Cookies but still cookies are insecure to use.
 
Write Cookies: 
 
        //---- Method one
        Response.Cookies["NameOfCookie"].Value = "ValueToBeStored";
        Response.Cookies["NameOfCookie"].Expires = DateTime.Now.AddDays(1);


        //-------- Method two
        //--- Create cookie object and pass name of the cookie and value to be stored.
        HttpCookie cookieObject = new HttpCookie("NameOfCookie", "ValueToBeStored");

        //---- Set expiry time of cookie.
        cookieObject.Expires.AddDays(5);

        //---- Add cookie to cookie collection.
        Response.Cookies.Add(cookieObject);
 
Read Cookies: 
 
        //--- Check if cookie exists or not
        if (Request.Cookies["NameOfCookie"] != null)
        {
            string value = Request.Cookies.Get("NameOfCookie").Value;
        }
 
Delete Cookies:
 
        //--- Get cookie Collection.
        HttpCookie cookieObj = Request.Cookies["NameOfCookie"];

        //--- To delete cookie we will add negative time.
        cookieObj.Expires = DateTime.Now.AddDays(-1);

        //---- Add cookie to cookie collection.
        Response.Cookies.Add(cookieObj);
 
While reading cookies make sure you pass the correct cookie name, which is used at the time of cookie creation.
 
In the above example we have created a single valued cookie however you can create cookie with more than one value using name-value pairs. 
 
 
Note: Never implement any important functionality in your website which relies on cookies as users can enable or disable cookies from their browsers. This will stops your code. However you can check whether a Browser Accepts Cookies.
 


cookies-best-example-in-asp-net-codingfusion
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice