asp.net Cookie operation class

  • 2020-05-07 19:29:28
  • OfStack


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 Action class  
/// </summary> 
public class Cookie 
{ 
/// <summary> 
///  save 1 a Cookie 
/// </summary> 
/// <param name="CookieName">Cookie The name of the </param> 
/// <param name="CookieValue">Cookie value </param> 
/// <param name="CookieTime">Cookie Expiration time ( hours ),0 Invalid to close the page </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) 
{ 
// There are two ways, number one 1 Methods set up Cookie Closing the browser won't clear it automatically at that time Cookie 
// The first 2 Method not set Cookie If you close the browser, it will clear automatically Cookie , But period of validity  
// How long has not been confirmed.  
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> 
///  achieve CookieValue 
/// </summary> 
/// <param name="CookieName">Cookie The name of the </param> 
/// <returns>Cookie The value of the </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> 
///  remove CookieValue 
/// </summary> 
/// <param name="CookieName">Cookie The name of the </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); 
} 
} 
}

Related articles: