C#自定义简化cookie类实例
程序员文章站
2023-12-03 10:54:22
本文实例讲述了c#自定义简化cookie类。分享给大家供大家参考。具体分析如下:
这个c#类封装了常用的cookie操作,包括读取cookie、写入cookie、设置co...
本文实例讲述了c#自定义简化cookie类。分享给大家供大家参考。具体分析如下:
这个c#类封装了常用的cookie操作,包括读取cookie、写入cookie、设置cookie过期时间等等。
using system; using system.web; namespace dotnet.utilities { public class cookiehelper { /// <summary> /// 清除指定cookie /// </summary> /// <param name="cookiename">cookiename</param> public static void clearcookie(string cookiename) { httpcookie cookie = httpcontext.current.request.cookies[cookiename]; if (cookie != null) { cookie.expires = datetime.now.addyears(-3); httpcontext.current.response.cookies.add(cookie); } } /// <summary> /// 获取指定cookie值 /// </summary> /// <param name="cookiename">cookiename</param> /// <returns></returns> public static string getcookievalue(string cookiename) { httpcookie cookie = httpcontext.current.request.cookies[cookiename]; string str = string.empty; if (cookie != null) { str = cookie.value; } return str; } /// <summary> /// 添加一个cookie(24小时过期) /// </summary> /// <param name="cookiename"></param> /// <param name="cookievalue"></param> public static void setcookie(string cookiename, string cookievalue) { setcookie(cookiename, cookievalue, datetime.now.adddays(1.0)); } /// <summary> /// 添加一个cookie /// </summary> /// <param name="cookiename">cookie名</param> /// <param name="cookievalue">cookie值</param> /// <param name="expires">过期时间 datetime</param> public static void setcookie(string cookiename, string cookievalue,datetime expires) { httpcookie cookie = new httpcookie(cookiename) { value = cookievalue, expires = expires }; httpcontext.current.response.cookies.add(cookie); } } }
希望本文所述对大家的c#程序设计有所帮助。
下一篇: C#移除所有事件绑定的方法