Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

Find If the Browser Accept Cookies

In web applications sometimes we need to find out that if the browser can accepts cookies. For this you can always use the following code:

Request.Browser.Cookies

which, will return true or false on the basic if the browser can accept cookies or not. But it does not tell that if the user has turned off accept cookies. So, it can be the case that the browser can accepts cookies but user is not allowing the browser to accept cookies; see the difference.

Request.Browser.Cookies will also return true even if you configure the browser not to accept any cookies. So, how to find if the user has configured the browser not to accept any cookies. Let's check out the code:

First Create the Cookie:

private void CreateCookie()

{ /*

* Please note that even if the browser does not accept cookies creating and attaching the

* cookie to the response will not throw any exception

* Request.Browser.Cookies only tells that if the browser is capable of creating cookies. But it does not tell that if the cookies

are being accepted by the user.*/

// create a cookie

// You can encrypt the cookie

HttpCookie cookie = new HttpCookie(cookieName, cookieValue);

// The above cookie is a session cookie meaning that once, you close the browser the cookie is gone.

// You can use cookie.Expires to set the expiration time on the cookie in which case it will last long :)

// add the cookie to the response

Response.Cookies.Add(cookie);

}

And now simply, read the cookie.

private bool DoesUserBrowserAcceptCookies()

{

bool result = false;

// Now read the cookie back

if (Request.Cookies[cookieName] != null)

{

if (Request.Cookies[cookieName].Name.Equals(cookieName))

result = true;

}

return result;

}

This ensures that the user is allowing us to create cookies as well as read the newly created cookies.

Now, if you configure the browser to not to accept cookies then the method DoesUserBrowserAcceptCookies will return false.

Published Thursday, December 14, 2006 11:40 PM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below