In asp.net, 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 whether a Cookie is accepted. This example contains two pages. On the first page, I wrote a Cookie and redirected the browser to the second page. On the second page, try to read the Cookie, redirect the browser to the first page, and add a query string variable with test results to the URL.
The code for checking whether the browser accepts cookies on the first page of asp.net is as follows:
- ProtectedSystem. Web. UI. WebControls. Label labelAcceptsCookies;
- Private VoidPage_Load (ObjectSender, System. EventArgs e)
- ...{
- If(! IsPostBack)
- ...{
- WriteCookie ();
- }
- }
-
- Private VoidWriteCookie ()
- ...{
- 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 (AcceptsCookies) that contains the test result ). 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 following example calls Response. Redirect to switch to the test page (TestForCookies. aspx ). The URL appended to the test page is the query string variable named redirect, which contains the URL of the current page, so that you can redirect to the 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 to test whether the browser accepts cookies:
- Private VoidPage_Load (ObjectSender, System. EventArgs e)
- ...{
- ReadCookie ();
- }
- Private VoidReadCookie ()
- ...{
- String redirect = Request. QueryString ["Redirect"];
- String acceptsCookies;
- // Do you want to accept cookies?
- If(Request. Cookies ["TestCookie"] =Null)
- // No Cookie, so you do not need to accept
- AcceptsCookies ="0";
- Else
- ...{
- AcceptsCookies ="1";
- // Delete the test Cookie
- Response. Cookies ["TestCookie"]. Expires = DateTime. Now. AddDays (-1 );
- }
- Response. Redirect (redirect +"? AcceptsCookies ="+ AcceptsCookies,True);
- }
In this way, you can determine whether the browser accepts cookies in ASP. NET.
- Implement code that prevents multiple page submissions in ASP. NET
- ASP. NET Server Control Development-Composite Control
- Introduction to "three-layer structure" in ASP. NET
- 26 methods for optimizing ASP. NET performance
- Comparison of html controls and web controls in ASP. NET