one way to determine whether a browser accepts cookies is to write a cookie before attempting to read the cookie. If you cannot read this cookie, you can assume that the browser does not accept cookies.
I've written a simple example to show how to test whether a Cookie is accepted. The 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 the Cookie, redirects the browser to the first page, and adds a query string variable with the test result to the URL.
the code for the first page is as 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"];
}
}
The first page tests whether there is a reply, and if not, searches for a query string variable (acceptscookies) that contains the results of the test. If the query string variable is not found, the test is not finished and the code writes a Cookie named "TestCookie". After writing out the Cookie, the example calls Response.Redirect to switch to the test page (testforcookies.aspx). The URL attached to the test page is a query string variable named redirect that contains the URL of the current page, which can be redirected to the page after the test is executed.
The test page can consist entirely 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;
Do you accept cookies?
if (request.cookies["TestCookie"] ==null)
No cookies, so no 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);
}