欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net Cookie操作类

程序员文章站 2024-03-09 10:56:11
复制代码 代码如下:using system; using system.collections.generic; using system.linq; using sys...
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.data;
using system.configuration;

namespace jhgl.smart
{
/// <summary>
/// cookie操作类
/// </summary>
public class cookie
{
/// <summary>
/// 保存一个cookie
/// </summary>
/// <param name="cookiename">cookie名称</param>
/// <param name="cookievalue">cookie值</param>
/// <param name="cookietime">cookie过期时间(小时),0为关闭页面失效</param>
public static void savecookie(string cookiename, string cookievalue, double cookietime)
{
httpcookie mycookie = new httpcookie(cookiename);
datetime now = datetime.now;
mycookie.value = cookievalue;

if (cookietime != 0)
{
//有两种方法,第一方法设置cookie时间的话,关闭浏览器不会自动清除cookie
//第二方法不设置cookie时间的话,关闭浏览器会自动清除cookie ,但是有效期
//多久还未得到证实。
mycookie.expires = now.adddays(cookietime);
if (httpcontext.current.response.cookies[cookiename] != null)
httpcontext.current.response.cookies.remove(cookiename);

httpcontext.current.response.cookies.add(mycookie);
}
else
{
if (httpcontext.current.response.cookies[cookiename] != null)
httpcontext.current.response.cookies.remove(cookiename);

httpcontext.current.response.cookies.add(mycookie);
}
}
/// <summary>
/// 取得cookievalue
/// </summary>
/// <param name="cookiename">cookie名称</param>
/// <returns>cookie的值</returns>
public static string getcookie(string cookiename)
{
httpcookie mycookie = new httpcookie(cookiename);
mycookie = httpcontext.current.request.cookies[cookiename];

if (mycookie != null)
return mycookie.value;
else
return null;
}
/// <summary>
/// 清除cookievalue
/// </summary>
/// <param name="cookiename">cookie名称</param>
public static void clearcookie(string cookiename)
{
httpcookie mycookie = new httpcookie(cookiename);
datetime now = datetime.now;

mycookie.expires = now.addyears(-2);

httpcontext.current.response.cookies.add(mycookie);
}
}
}