One way to determine whether the browser accepts a cookie is to write a cookie before trying to read it. If the cookie cannot be read, the browser may not accept the cookie.
I wrote a simple example to illustrate how to test cookies.
Whether it is accepted. This example contains two pages. On the first page, I wrote a cookie and redirected the browser to the second page. The second page tries to read this
Cookie to redirect the browser to the first page, and add a query string variable with test results to the URL.
TheCodeAs follows:
Protected System. Web. UI. webcontrols. Label labelacceptscookies;
Private Void Page_load ( Object Sender, system. eventargs E)
... {
If(!Ispostback)
...{
Writecookie ();
}
}
Private Void Writecookie ()
... {
If (Request. querystring [ " Acceptscookies " ] = Null )
... {
Response. Cookies [ " Testcookie " ]. Value = " OK " ;
Response. Cookies [ " Testcookie " ]. Expires = Datetime. Now. addminutes ( 1 );
Response. Redirect ( " Cookieread. aspx? Redirect = " + Server. urlencode (request. url. tostring ()));
}
Else
... {
Labelacceptscookies. Text= "Accept cookie ="+Request. querystring ["Acceptscookies"];
}
}
On the first page, test whether there is a response. If not, search for the query string variable that contains the test result (Acceptscookies
). If the query string variable is not found, the test is not complete, and the code writes a cookie named "testcookie. After the cookie is written, the example callResponse. RedirectTo switch to the test page (testforcookies. aspx ). The URL appended to the test page is namedRedirect
The query string variable, which contains the URL of the current page, so that you can redirect to this page after the test is executed.
The test page can be fully composed of code and does not need to contain controls. The following code is used:
Private Void Page_load ( Object Sender, system. eventargs E)
... {
Readcookie ();
}
Private Void Readcookie ()
... {
String redirect = Request. querystring [ " Redirect " ];
String acceptscookies;
// Accept cookies?
If (Request. Cookies [ " Testcookie " ] = Null )
// No cookie, so you do not need to accept
Acceptscookies = " 0 " ;
Else
... {
Acceptscookies = " 1 " ;
// Delete test cookie
Response. Cookies [ " Testcookie " ]. Expires = Datetime. Now. adddays ( - 1 );
}
Response. Redirect (redirect + " ? Acceptscookies = " + Acceptscookies, True );
}