Check if browser accepts cookies in asp .net

In this asp .net tutorial we will learn how to check whether cookies are enabled in browser or not. Cookies are small text files stored in user’s computer, used to store small amount of information by websites. Now a days most websites relies on cookies to store small amount of data. You can store single valued cookies and multiple valued cookies in asp .net.  As cookies are stored by web browser, these can be enabled or disabled by the end user. 

 

If your website functionality relies on cookies it is better to check whether cookies are enabled or disabled in web browser and prompt users if cookies are disabled from web browser.
 

Lets create a small application which checks whether cookies are enabled in browser or not and display status to the user.


Step1: Create a new asp .net website.


Step2: Create a label in your aspx page to display message.

 


 

Step3: Place this code in your Page_Load() method to check if cookies are enabled or not.

 

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["CheckCookie"] == null)
        {
            if (string.IsNullOrWhiteSpace(Request.QueryString["cookie"]))
            {
                Response.Cookies["CheckCookie"].Value = "Yes";
                Response.Redirect(Request.Url.ToString() + "?cookie=created", true);
            }
            else if (Request.QueryString["cookie"].Equals("created"))
            {
                lblResult.Text = "Cookies enabled?: No";
            }
        }
        else
        {
            lblResult.Text = "Cookies enabled?: Yes";
        }
    }

 

By the above example you can see how easily we can determine whether cookies are enabled or disabled in browser or note.


Tip: You might interested in How to encrypt and decrypt cookies value in asp .net.

Best quality Asp .Net Ajax Control Toolkit tutorials.
Thanks. This is really good piece of code to check the cookies enable/disable. Suppose in an application, multiple pages have cookies. So does we need to run this code on each page? I know we can have set public variable on first request but what if users disable the cookies after first check?
21-Jan-2015 From  Jagz W

Give your valuable comments.

Name
Email
Comment
7 + 6 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice