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

C#自定义简化cookie类实例

程序员文章站 2023-12-12 15:11:04
本文实例讲述了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#程序设计有所帮助。

上一篇:

下一篇: