Determining Whether a Users Browser Accepts Cookies Using asp.net and C#.
Users can set their browser to refuse cookies. No error is raised if a cookie cannot be written.If you have a web page that requires cookies or session variables to work properly,then you might want to check if the user's browser is configured to accept cookies. The browser does not send any information to the server about its current cookie settings. The best way to determine if cookies are accepted by browser is trying to write a cookie and then trying to read it back again. If you are not able to read the cookie you wrote, you assume that cookies are turned off in the user's browser.The below code shows test whether cookies are accepted by user browser.
The code contains two pages. first page for writing a cookie, and then it redirects the browser to the next page. The second page will try to read the cookie.
The first page IsAcceptCookie.aspx code looks like this .
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["IsAccepts"] == null)
{
Response.Cookies["CheckCookie"].Value = "ok";
Response.Cookies["CheckCookie"].Expires =
DateTime.Now.AddMinutes(1);
Response.Redirect("CheckCookies.aspx?redirect=" +
Server.UrlEncode(Request.Url.ToString()));
}
else
{
lblresult.Text = "Accept cookies = " +
Server.UrlEncode(
Request.QueryString["IsAccepts"]);
}
}
}
The second page CheckCookies.aspx code looks like this
protected void Page_Load(object sender, EventArgs e)
{
string redirect = Request.QueryString["redirect"];
string IsacceptsCookies;
if(Request.Cookies["CheckCookie"] ==null)
IsacceptsCookies = "no";
else
{
IsacceptsCookies = "yes";
// Now you can Delete test cookie.
Response.Cookies["CheckCookie"].Expires =
DateTime.Now.AddDays(-1);
}
Response.Redirect(redirect + "?IsAccepts=" + IsacceptsCookies,
true);
}
Code Explanation:--
The page first checks if this is a postback, and if not, the page will check for the query string name IsAccepts that contains results of the test. If it find no query string variable, then it writes a cookie named CheckCookie. After writing cookie, the page Redirect to the second page CheckCookies.aspx. the CheckCookies.aspx page will read the cookie if it exists it will deleted the cookie and redirect to the first page with query string name IsAccepts having value yes or no the first page will check and display the result.