在ASP.NET中,确定用户浏览器是否启用了cookie的最佳方法是什么?
设置一个cookie,强制重定向到某个检查页面并检查cookie。
或在每个页面加载时设置cookie(如果尚未设置)。例如,我假设这是为了检查是否支持cookie,以便在用户尝试登录时显示消息,提示他们需要启用cookie。如果访客用户尚未设置cookie,则将登录cookie设置为一些默认值。然后在登录页面上,检查用户cookie,如果未设置,则显示您的消息。
@Mattew说得对,找出答案的唯一方法是设置一个Cookie,重定向,然后检查它。以下是一个C#函数,可以在页面加载事件中使用它进行检查:
private bool cookiesAreEnabled()
{
bool cookieEnabled = false;
if(Request.Browser.Cookies)
{
//Your Browser supports cookies
if (Request.QueryString["TestingCookie"] == null)
{
//not testing the cookie so create it
HttpCookie cookie = new HttpCookie("CookieTest","");
Response.Cookies.Add(cookie);
//redirect to same page because the cookie will be written to the client computer,
//only upon sending the response back from the server
Response.Redirect("Default.aspx?TestingCookie=1")
}
else
{
//let's check if Cookies are enabled
if(Request.Cookies["CookieTest"] == null)
{
//Cookies are disabled
}
else
{
//Cookies are enabled
cookieEnabled = true;
}
}
}
else
{
// Your Browser does not support cookies
}
return cookieEnabled;
}
function cookiesAreEnabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0;
if (typeof navigator.cookieEnabled == "undefined" && cookieEnabled == 0){
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? 1 : 0;
}
return cookieEnabled == 1;
}
本质上与meda相同的解决方案,但是使用VB.NET实现:
Private Function IsCookieDisabled() As Boolean
Dim currentUrl As String = Request.RawUrl
If Request.Browser.Cookies Then
'Your Browser supports cookies
If Request.QueryString("cc") Is Nothing Then
'not testing the cookie so create it
Dim c As HttpCookie = New HttpCookie("SupportCookies", "true")
Response.Cookies.Add(c)
If currentUrl.IndexOf("?") > 0 Then
currentUrl = currentUrl + "&cc=true"
Else
currentUrl = currentUrl + "?cc=true"
End If
Response.Redirect(currentUrl)
Else
'let's check if Cookies are enabled
If Request.Cookies("SupportCookies") Is Nothing Then
'Cookies are disabled
Return True
Else
'Cookies are enabled
Return False
End If
End If
Else
Return True
End If
End Function
我认为如果我们能在Global.ASAX的会话开始时保存cookie,并在页面上读取它,那不是最好的方式吗?
编写一个cookie,重定向,看看能否读取cookie。
meda的C#函数是可行的,但你需要更改以下这一行:
HttpCookie cookie = new HttpCookie("","");
为
HttpCookie cookie = new HttpCookie("CookieTest","CookieTest");
您还可以检查Request.Browser.Cookies
的值。如果为true,则浏览器支持cookies。
这是最好的方法
摘自http://www.eggheadcafe.com/community/aspnet/7/42769/cookies-enabled-or-not-.aspx
function cc()
{
/* check for a cookie */
if (document.cookie == "")
{
/* if a cookie is not found - alert user -
change cookieexists field value to false */
alert("COOKIES need to be enabled!");
/* If the user has Cookies disabled an alert will let him know
that cookies need to be enabled to log on.*/
document.Form1.cookieexists.value ="false"
} else {
/* this sets the value to true and nothing else will happen,
the user will be able to log on*/
document.Form1.cookieexists.value ="true"
}
}
感谢 Venkat K