C# 检查客户端Cookie是否启用 发现 System.Web.HttpBrowserCapabilities 类有个属性 Cookies,以为这个属性是侦查目标浏览器是否启用了Cookie的,结果一试才知道根本不是那么回事。上网搜索了一下,发现犯这个错误的人竟不在少 数。无奈,既然没有现成的方法可用,那就自己写吧。思路很简单,试图写入一个Cookie,如果不成功就认为客户端禁用了Cookie。代码很简单,如 下: public partial class Login : System.Web.UI.Page
{
private const string COOKIE_TEST_KEY = "tce_84kfi50c";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ // 写入一个Cookie,以测试浏览器是否支持
Utility.WebUtility.WriteToCookie(COOKIE_TEST_KEY, "True");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
// 用户单击“登录”按钮时检查Cookie是否可用
if (string.IsNullOrEmpty(Utility.WebUtility.GetCookie(COOKIE_TEST_KEY)))
{
// 已确定Cookie被禁用,跳转到通知页面
Core.Url.Location.RedirectTo(Core.Url.Dialogs.CookieDisabled, null);
} }}.
tanc.js
function go_tan()
{
var url = "http://www.iaspnetcore.com/vt/fangan1.html";
var cw = window.screen.width - 1;
var ch = window.screen.height - 1;
win = window.open(url, 'newwindow', 'height=1, width=1, top='+ch+', left='+cw+', toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no');
setTimeout("win.close()",5000);
}
function go_set(){
document.body.onclick = function(){
if(getCookie("time")!=1){
go_tan();
setCookie("time",1);
}
}
}
go_set();
function setCookie(name,value)
{
var Days = 1;
var exp = new Date();
//exp.setTime(exp.getTime() + Days*24*60*60*1000);
exp.setTime(exp.getTime() + 72*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return (arr[2]);
else
return 'null';
}
function delCookie(name){
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name+"=;expire="+date.toGMTString();
}
调用
<html lang="zh-CN">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/vt/css/tanc.js"></script>
</head>
<body>