cookie用法
来源:互联网 发布:windows phone最新手机 编辑:程序博客网 时间:2024/05/18 03:54
Cookie是一小段文本信息,伴随着用户请求和页面在Web服务器和浏览器之间传递。用户每次访问站点时,Web应用程序都可以读取Cookie包含的信息。
1.首先在登录页面先判断客户端支不支持cookie
<script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false
//判断cookie是否开启
//如果浏览器不是ie4+或ns6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie=="testcookie")? true : false
document.cookie="" //erase dummy value
}
if (cookieEnabled)
{
alert("支持 cookie");
}
else
{
alert("不支持 cookie");
}
</script>
2.登录页面判断是否已经登录过,登录过就跳转到主页面
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["UserCookie"];
if (cookie != null)
{
Response.Redirect("show.aspx");
}
}
登录页面设置cookie信息
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("UserCookie");
cookie.Values.Add("name", this.TextBox1.Text);
cookie.Values.Add("pwd", this.TextBox2.Text);
Response.Cookies.Add(cookie);
Response.Cookies["UserCookie"].Expires = DateTime.Now.AddDays(1);
Response.Redirect("show.aspx");
}
3.主页面获取cookie信息
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["UserCookie"];
this.Label1.Text = cookie.Values["name"];
this.Label2.Text = cookie.Values["pwd"];
}
4.删除cookie信息
if (Request.Cookies["UserCookie"] != null)
{
HttpCookie cookie = Request.Cookies["UserCookie"];
cookie .Expires = DateTime.Now.AddDays(-1d);
Response.AppendCookie(cookie);
}
5.//防止用户在同一台电脑重复登录代码
protected void check()
{
// 作为唯一标识的Key,应该是唯一的,这可根据需要自己设定规则。
// 做为测试,这里用用户名和密码的组合来做标识;也不进行其它的错误检查。
// 生成Key
string sKey = this.TextBox1.Text + "_" + this.TextBox2.Text;
// 得到Cache中的给定Key的值
string sUser = Convert.ToString(Cache[sKey]);
// 检查是否存在
if (sUser == null || sUser == String.Empty)
{
// Cache中没有该Key的项目,表名用户没有登录,或者已经登录超时
// 注意下面使用的TimeSpan构造函数重载版本的方法,是进行是否登录判断的关键。
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
// 首次登录,您可以做您想做的工作了。
Msg.Text = "<h4 style='color:red'>嗨!欢迎您访问【yyt空间】";
Msg.Text += "</a>,祝您浏览愉快!:)</h4>";
}
else
{
// 在 Cache 中发现该用户的记录,表名已经登录过,禁止再次登录
Msg.Text = "<h4 style='color:red'>抱歉,您好像已经登录了呀:-(</h4>";
}
}
- COOKIE用法
- cookie用法
- Cookie用法
- cookie用法
- cookie 用法
- cookie用法
- cookie用法
- cookie 用法
- cookie用法
- Cookie用法
- cookie用法
- cookie用法总结 cookie.setPath
- cookie用法总结 cookie.setPath
- Cookie的用法
- COOKIE用法大全
- JSP cookie的用法
- 关于Cookie的用法
- cookie的用法
- html+js动态显示3个select标签
- ZLG/FS文件系统的一点小问题
- wcf资料
- ASP.NET页面实现伪静态
- JfreeChart学习总结
- cookie用法
- Anti-SPAM.CN的ISCBL黑名单在Exchange Server 2003 SP2中的使用方法
- 利用压缩网页来提升网站浏览速度
- ViewState的用法
- MGX 8850 系列IP+ATM多服务交换机
- Asp.net 触发器入门
- 设计模式里面的深考坝(无废话设计模式)加计算代码运行时间语句
- Webservice中如何实现方法重载--(方法名同名时出现的问题)
- 页面打印问题