ASP.NET下对cookies的操作实现代码

代码如下:

public class BsCookie
{
//操作的cookie
private HttpCookie _theCookie;
//对应的cookie的名称
private string _cookieName;
private bool _httpOnly = true;
/// <summary>
/// 是否只允许在服务器端访问,默认只允许在服务端访问
/// </summary>
public bool HttpOnly
{
get { return _httpOnly; }
set { _httpOnly = value; }
}
private double _expireMinutes;
/// <summary>
/// Cookies有效的存放时间,以分钟表示
/// </summary>
public double ExpireMinutes
{
get { return _expireMinutes; }
set { _expireMinutes = value; }
}
public BsCookie(string name,double expireMinutes)
{
_cookieName = name;
_expireMinutes = expireMinutes;
}
/// <summary>
/// 读取对应的cookie
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private HttpCookie GetCookieReq()
{
HttpRequest request = HttpContext.Current.Request;
if (request != null)
{
HttpCookie cookie = request.Cookies[_cookieName];
if (cookie != null)
{
return cookie;
}
}
return null;
}
/// <summary>
/// 设置对应的cookie
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private HttpCookie GetCookieResponse()
{
HttpResponse response = HttpContext.Current.Response;
if (response != null)
{
HttpCookie cookie = response.Cookies[_cookieName];
if (cookie != null)
{
return cookie;
}
}
return new HttpCookie(_cookieName);
}
/// <summary>
/// 仅设置主键的
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="exMinutes"></param>
public void SetCookie(string value)
{
_theCookie = GetCookieResponse();
_theCookie.Value = HttpUtility.HtmlEncode(AllCommon.Encrypt(value));
if (Math.Abs(_expireMinutes) > 1)
{
_theCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
}
_theCookie.HttpOnly = _httpOnly;
}
/// <summary>
/// 设置一组主键
/// </summary>
/// <param name="name"></param>
/// <param name="keys"></param>
/// <param name="exMinutes"></param>
public void SetCookie(Hashtable keys)
{
_theCookie = GetCookieResponse();
foreach (DictionaryEntry de in keys)
{
_theCookie.Values[de.Key.ToString()] = HttpUtility.HtmlEncode(AllCommon.Encrypt(de.Value.ToString()));
}
if (Math.Abs(_expireMinutes) > 1)
{
_theCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
}
_theCookie.HttpOnly = _httpOnly;
}
/// <summary>
/// 获取单一的cookie主键值
/// </summary>
/// <param name="name"></param>
/// <param name="exMinutes">需要延长的cookie的默认时间</param>
/// <returns></returns>
public string GetCookie()
{
_theCookie = GetCookieReq();
if (_theCookie == null)
{
return string.Empty;
}
string thevalue = AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Value));
if (thevalue.Length > 0)
{
HttpCookie serverCookie = GetCookieResponse();
if (Math.Abs(_expireMinutes) > 1)
{
serverCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
}
}
return thevalue;
}
/// <summary>
/// 获取一组对应的cookie值
/// </summary>
/// <param name="name"></param>
/// <param name="exMinutes"></param>
/// <returns></returns>
public Hashtable GetCookiesKeys()
{
_theCookie = GetCookieReq();
if (_theCookie == null)
{
return null;
}
string[] keys = _theCookie.Values.AllKeys;
if (keys.Length > 0)
{
Hashtable keyHash = new Hashtable();
foreach (string key in keys)
{
keyHash.Add(key, AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Values[key])));
}
HttpCookie serverCookie = GetCookieResponse();
if (Math.Abs(_expireMinutes) > 1)
{
serverCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
}
return keyHash;
}
return null;
}
/// <summary>
/// 获取一组里面的单一个值
/// </summary>
/// <param name="keyname"></param>
/// <param name="exMinutes"></param>
/// <returns></returns>
public string GetCookieKV(string keyname)
{
_theCookie = GetCookieReq();
if (_theCookie == null)
{
return string.Empty;
}
string result=AllCommon.Decrypt(HttpUtility.HtmlDecode(_theCookie.Values[keyname]));
if (result.Length > 0)
{
HttpCookie serverCookie = GetCookieResponse();
if (Math.Abs(_expireMinutes) > 1 && serverCookie != null)
{
serverCookie.Expires = DateTime.Now.AddMinutes(_expireMinutes);
}
}
return result;
}
}

演示Asp.Net中对Cookie的基本操作。


代码如下:

Imports System.Web.HttpContext
Public Class CookieFramework
'写入单个Cookie
Public Shared Function WriteCookie(ByVal CookieName As String, ByVal CookieValue As String, ByVal ExpiresDate As Integer) As Boolean
Dim aCookie As New HttpCookie(CookieName)
aCookie.Value = CookieValue
aCookie.Expires = DateTime.Now.AddDays(ExpiresDate)
System.Web.HttpContext.Current.Response.Cookies.Add(aCookie)
End Function

'给Cookie集合添加子项
Public Shared Function WriteCookies(ByVal CookieName As String, ByVal CookieItem As String, ByVal ItemValue As String, ByVal ExpiresDate As Integer) As Boolean
Dim aCookie As HttpCookie
If Current.Request.Cookies(CookieName) Is Nothing Then
aCookie = New HttpCookie(CookieName)
Else
aCookie = Current.Request.Cookies(CookieName)
End If
aCookie.Values(CookieItem) = ItemValue
aCookie.Expires = DateTime.Now.AddDays(ExpiresDate)
System.Web.HttpContext.Current.Response.Cookies.Add(aCookie)
End Function
'读取单个Cookie
Public Shared Function ReadCookie(ByVal CookieName As String) As String
If Current.Request.Cookies(CookieName) Is Nothing Then
Return Nothing
Else
Return Current.Request.Cookies(CookieName).Value
End If
End Function

'读取Cookie集合中的子项内容
Public Shared Function ReadCookies(ByVal CookieName As String, ByVal CookieItem As String) As String
If Current.Request.Cookies(CookieName) Is Nothing Then
Return Nothing
Else
If Current.Request.Cookies(CookieName).Values(CookieItem) Is Nothing Then
Return Nothing
Else
Return Current.Request.Cookies(CookieName).Values(CookieItem)
End If
End If
End Function
'删除整个Cookie
Public Shared Function DeleteCookie(ByVal CookieName As String) As Boolean
Dim aCookie As New HttpCookie(CookieName)
Dim i As Integer
Dim limit As Integer = Current.Request.Cookies.Count - 1
For i = 0 To limit
aCookie = Current.Request.Cookies(i)
aCookie.Expires = DateTime.Now.AddDays(-1)
Current.Response.Cookies.Add(aCookie)
Next
End Function
'删除Cookie集合中的子项
Public Shared Function DeleteCookies(ByVal CookieName As String, ByVal ItemName As String) As Boolean
Dim aCookie As HttpCookie = Current.Request.Cookies(CookieName)
aCookie.Values.Remove(ItemName)
aCookie.Expires = DateTime.Now.AddDays(1)
Current.Response.Cookies.Add(aCookie)
End Function
End Class

(0)

相关推荐

  • asp.net利用cookie保存用户密码实现自动登录的方法

    本文实例讲述了asp.net利用cookie保存用户密码实现自动登录的方法.分享给大家供大家参考.具体分析如下: 在asp.net中可以用cookie保存用户的帐户密码实现自动登录的功能,但是需要强调一下,cookie在客户端保存,是不安全的,推荐使用md5加密保存. 下面分析一下在asp.net中cookie的创建.提取与销毁的方法: 创建cookie 复制代码 代码如下: //向客户端写入Cookie HttpCookie hcUserName1 = new HttpCookie("unam

  • asp.net各种cookie代码和解析实例

    Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一.Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一起发送到服务器.浏览器对 Cookie 的大小有限制,因此,只有不超过 4096 字节才能保证被接受. 编写Cookie 复制代码 代码如下: //方式1:Response.Cookies["username"].value="mike";Response.Cookie

  • asp.net中使用cookie传递参数的方法

    本文实例讲述了asp.net中使用cookie传递参数的方法.分享给大家供大家参考.具体如下: //传值 HttpCookie cookie = new HttpCookie("mycookie"); cookie.Value = "cookie值"; Response.AppendCookie(cookie); Response.Redirect("index.aspx"); //接收 Request.Cookies["mycooki

  • asp.net 操作cookie的简单实例

    复制代码 代码如下: protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            HttpCookie cookie = Request.Cookies["loginInfo"]; if (cookie != null)            {                cb_repwd.Checked = true;          

  • ASP.NET之Response.Cookies.Remove 无法删除COOKIE的原因

    例子如下: 复制代码 代码如下: protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        HttpCookie UserInfo = new HttpCookie("UserInfo");        UserInfo.Value = "bdstjk";        Response.Cookies.Add(UserInfo);    } } pr

  • Asp.net内置对象之Cookies(简介/属性方法/基本操作及实例)

    一.了解Cookies对象 Cookies是由Web服务器管理的存放在客户计算机中的一个数据集合.这些数据是客户端.服务器端相关的.也就是说客户浏览器每登录一个网站,在Cookies中就会保存客户浏览器与该网站的相关信息.即使客户用同一个浏览器登陆了多个网站,在Cookies中依然会保存浏览器与多个网站的相关信息,但Cookies中这些信息的管理是有序的,当客户浏览器再次登录某网站时,只有Cookies中相对应的信息会发生作用. Cookies是Web应用程序设计的一项很重要的技术,当Web服务

  • ASP.NET笔记之页面跳转、调试、form表单、viewstate、cookie的使用说明

    1.页面跳转: (1 服务器传输 server.Transer(http://www.jb51.net);在定向到新页面后,还是会显示原来的URL,浏览器返回不会退回到原页面,历史记录也不会记录. 应用于完整的控制传输,例如安装向导. (2 超链接 (3 浏览器重定向 Redirect ,速度快,没有发送到服务器 (4 跨页发送 PostBackUrl="http://www.jb51.net" /> IsCrossPagePostBack用来判断是否为跨页提交 IsPostBa

  • asp.net中的cookie使用介绍

    一.cookie导读,理解什么是cookie 1.什么是cookie:cookie是一种能够让网站服务器把少量数据(4kb左右)存储到客户端的硬盘或内存.并且读可以取出来的一种技术. 2.当你浏览某网站时,由web服务器放置于你硬盘上的一个非常小的文本文件,它可以记录你的用户id.浏览过的网页或者停留的时间等网站想要你保存的信息.当你再次通过浏览器访问该网站时,浏览器会自动将属于该网站的cookie发送到服务器去,服务器通过读取cookie,得知你的相关信息,就可以做出相应的动作.比如,显示欢迎

  • ASP.NET下对cookies的操作实现代码

    复制代码 代码如下: public class BsCookie { //操作的cookie private HttpCookie _theCookie; //对应的cookie的名称 private string _cookieName; private bool _httpOnly = true; /// <summary> /// 是否只允许在服务器端访问,默认只允许在服务端访问 /// </summary> public bool HttpOnly { get { retu

  • asp快速开发方法之数据操作实例代码第1/3页

    这是我自己的心得,给大家作个参考. 我的目的是让开发变得简单,尽可能少地考虑实现语句,更多地把精力用于思考业务逻辑.希望我的文章对大家有所启发和帮助. 如果你对ASP不熟悉,可以先看以下教程: 1.http://布鲁斯狼的ASP编程入门进阶 2.www.w3schools.com的ASP教程(英文\中文),查看更多 好吧,让我们进入正题: 先看以下例子: <% db_path = "database/cnbruce.mdb" Set conn= Server.CreateObje

  • asp.net下实现URL重写技术的代码

    URL 重写是截取传入 Web 请求并自动将请求重定向到其他 URL 的过程.   比如浏览器发来请求hostname/101.aspx ,服务器自动将这个请求中定向为http://hostname/list.aspx?id=101. url重写的优点在于:     缩短url,隐藏实际路径提高安全性     易于用户记忆和键入.      易于被搜索引擎收录 二 实现url重写的基本方法    下载MS的URLRewriter.dll,放到你的web程序的bin下 下载地址1:http://w

  • asp.net下按钮点击后禁用的实现代码

    一.让按钮在点击后用脚本使其禁用: 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DisableButton.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//

  • jquery下json数组的操作实现代码

    今天试过json[i].remove(),json.remove(i)之后都不行,看网页的DOM对象中好像JSON数据是以数组的形式出现的,查阅了下相关JS中数组的操作一试果然很爽. 记录下来. 1.数组的创建 复制代码 代码如下: var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限,是长度 var arrayObj = new Array([element0[,

  • asp.net下使用AjaxPro实现二级联动代码

    复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %> <!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1

  • asp.net下中文验证码,免费开源代码

    using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.Ht

  • 用js脚本控制asp.net下treeview的NodeCheck的实现代码

    增加CheckBox联动的情况选择: 1.单选TreeView中的任一节点 2.当一节点CheckBox属性值改变时:子节点的CheckBox属性值跟随其改动,父节点不变; 父节点的所有子节点的CheckBox属性值都为false时才为false;有一个子节点的CheckBox属性值true时则为true. 3.当一节点CheckBox属性值改变时:子节点.父节点的CheckBox属性值跟随其改动; 父节点的所有子节点的CheckBox属性值都为false时才为false;有一个子节点的Chec

  • asp.net下获取浏览器类型的实现代码

    相关代码: 复制代码 代码如下: if (Page.Request.Browser.EcmaScriptVersion.Major > 0 && Page.Request.Browser.W3CDomVersion.Major > 0)//判断是否支持脚本 { Response.Write("浏览器名称与版本号:" + Page.Request.Browser.Type + "<br />"); Response.Write(

  • asp.net Execl的添加,更新操作实现代码

    using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.Ht

随机推荐