In earlier articles, we learnt how to create, read, expire cookies and limit the scope of the cookies to a particular folder of the website and domain . In this article we are going to learn how to find out if user’s browser accepts the cookie or not.
Introduction
A Cookie is a small amount of text that attached to the requet and response in between browser and the server. This small amount of text can be read by the application whenever user browse the it. Please note that cookie is not a good medium to store the confidential data as it is stored into the user browser.
Let's learn how to find out if user’s browser accepts the cookie or not. In order to do this we shall prepare a sample page and below is the code.
ASPX PAGE
<asp:Label ID="lblMessage" runat="server" EnableViewState="false" />
In the above code snippet, we have a asp:Label control.
CODE BEHIND
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"))
{
lblMessage.Text = "Cookie enabled?: No";
}
}
else
{
lblMessage.Text = "Cookie enabled?: Yes";
}
}
In the above code snippet, we have a Page_Load event in which we are first checking for the “CheckCookie” cookie, if it is null then checking for the “cookie” querystring value. If the “cookie” querystring value is null or empty we are creating a cookie named “CheckCookie” and redirecting on the same page with “cookie=created” querystring.
Get video tutorials of hundreds of ASP.NET Tips and Tricks like this here.
When this page will be loaded in the browser again, there might be two case.
Case 1 : If cookie is enabled in the browser
The first condition of Request.Cookies[“Check Cookie”] will not be null and it will go to the else block and write messge “Cookie enabled? : Yes”.
Case: If cookie is disabled in the browser
The first condition of Request.Cookies[“Check Cookie”] will be null as cookie will not be created in the browser. So it will check for the “cookie” querystring, naturally it will not be null as its value will be “created” so the else if block code executes and writes message “Cookie enabled?: No”.
OUTPUT

In case you have missed articles series on Cookies, start from here.
Thanks for reading, let me know if you have any question related with cookies and I shall try to respond.