50% OFF!!!

Sunday, January 31, 2010

Asp.Net - check/validate cookies support

Here is a code for checking/validating that user device (browser) supports cookies. in other words this code checks if cookies are enabled on the browser.

Here the code implemented in the Login page:
    // Constants:
    protected const string QUERYSTRING_CHECK_COOKIE = "checkcookie";
    protected const string TEST_COOKIE_NAME = "check_cookie";
    protected const string TEST_COOKIE_VALUE = "ok";

    // On-load event, at page load:
    protected override void OnLoad(EventArgs p_eventArgs)
        if (IsPostBack == false)
            // Check if browser support cookies
            if (Request[QUERYSTRING_CHECK_COOKIE] == null)
                // try to insert cookie:
                Response.Cookies.Add(new HttpCookie(TEST_COOKIE_NAME, TEST_COOKIE_VALUE));
                string newUrl = string.Format("Login.aspx?{1}=1", QUERYSTRING_CHECK_COOKIE);
                this.Redirect(newUrl, true);
                // here, client sould contain test cookie:
                HttpCookie cookie = Request.Cookies[TEST_COOKIE_NAME];
                bool isCookieEnabled = cookie != null && cookie.Value == TEST_COOKIE_VALUE;
                if (isCookieEnabled == false)
                    // cookies are disabled!!! show error message
                    Label1.Text = "Device NOT support Cookies!";


You can implement this also in other pages than Login page.

1 comment:

  1. nice work.
    I used this function at my login page (the first access to my application), and after finding that the mobile device not support cookies, i display NOT-SUPPORTED-DEVICE message to the mobile-user.

    I saw you didn't set cookie expiration time, so i set it to 10 minutes, so:
    ==> on SONY-ERICSSON devices, it did not worked! the device igonore the 10 minutes and do not insert the test cookie. I changed it to 2 days, and it worked!
    (note that if the cookie is set to 2 days, and in this range the user set its device to disable-cookies, the code won't work)