栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

在程序中使用Cookie集合(定义/新建/删除)及案例讲解

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在程序中使用Cookie集合(定义/新建/删除)及案例讲解

在程序开发中,使用cookie时,很少使用如http://jb51.net/article/33590.htm的写法。习惯写成cookie集合,什么叫做cookie集合,即是说一个cookie,它拥有多个值。下面一系列演示,是怎样创建cookie集合与使用。
复制代码 代码如下:
InsusBiz
using System;
using System.Web;
///
/// Summary description for InsusBiz
///

public class InsusBiz
{
private static HttpResponse Response
{
get
{
return HttpContext.Current.Response;
}
}
private static HttpRequest Request
{
get
{
return HttpContext.Current.Request;
}
}
//定义一个cookie集合
private static Httpcookie Insuscookie
{
get
{
return Request.cookies["Insuscookie"] as Httpcookie;
}
set
{
if (Request.cookies["Insuscookie"] != null)
{
Request.cookies.Remove("Insuscookie");
}
Response.cookies.Add(value);
}
}
//New cookie集合
private static Httpcookie NewInsuscookie
{
get
{
Httpcookie httpcookie = new Httpcookie("Insuscookie");
return httpcookie;
}
}
//Remove cookie集合
public static void RemoveInsuscookie()
{
if (Insuscookie == null)
Response.cookies.Remove("Insuscookie");
else
Response.cookies["Insuscookie"].Expires = DateTime.Now.AddDays(-1);
}
//创建一个cookie,判断用户登录状态
public static bool LoginOk
{
get
{
return Insuscookie == null ? false : bool.Parse(Insuscookie.Values["LoginOk"]);
}
set
{
Httpcookie httpcookie = Insuscookie == null ? NewInsuscookie : Insuscookie;
httpcookie.Values["LoginOk"] = value.ToString();
Insuscookie = httpcookie;
}
}
//创建登录用户的帐号,整站使用
public static string MemberId
{
get
{
return Insuscookie == null ? string.Empty : Insuscookie.Values["MemberId"];
}
set
{
Httpcookie httpcookie = Insuscookie == null ? NewInsuscookie : Insuscookie;
httpcookie.Values["MemberId"] = value;
Insuscookie = httpcookie;
}
}
//如果还有整站使用的cookie可以写在此,可以参考LoginOK或MemberId的写法。
}

在应用时,你会看到InsusBiz类别下有LoginOk,MemberId和RemoveInsuscookie等属性:
 
在程序中怎样使用这些cookie呢?如在登录验证成功之后,你需要把登录状态与登录的ID写入cookie中
InsusBiz.LoginOk = true;
InsusBiz.MemberId = xxx;
在判断用户是否登录时,可以这个去判断:
复制代码 代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!InsusBiz.LoginOk)
{
//你没有登录
}
}

如果想在任何位置,想取出登录ID:
复制代码 代码如下:
string memberId = InsusBiz.MemberId;

最后想说的,你想移除Cooke,就可以使用InsusBiz.RemoveInsuscookie就可以了,因为它会把cookie的过期时间变更为过去。这个通常应用在用户Sign out的事件上。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/58074.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号