This article shares a friend's use of the asp.net cookie-related articles. If you have any need, refer to the related articles.
The Code is as follows: |
Copy code |
Using System; Using System. Collections. Generic; Using System. Linq; Using System. Web; Using System. IO; Using System. Runtime. Serialization; Using System. Runtime. Serialization. Formatters. Binary; 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 Bll { /// <Summary> /// Cookie operation class /// </Summary> Public class CookieHelper { # Region save Cookie /// <Summary> /// Save the Cookie /// </Summary> /// <Param name = "CookieName"> Cookie name </param> /// <Param name = "CookieValue"> Cookie value </param> /// <Param name = "CookieTime"> Cookie expiration time (hours). 0 indicates that the page is disabled. </param> Public static void SaveCookie (string CookieName, object CookieValue, double CookieTime) { HttpCookie myCookie = new HttpCookie (CookieName ); DateTime now = DateTime. Now; MyCookie. Value = ConvertObjectToString (CookieValue ); If (CookieTime! = 0) MyCookie. Expires = now. AddHours (CookieTime ); If (HttpContext. Current. Response. Cookies [CookieName]! = Null) HttpContext. Current. Response. Cookies. Remove (CookieName ); HttpContext. Current. Response. Cookies. Add (myCookie ); } Private static string ConvertObjectToString (object CookieValue) { BinaryFormatter bf = new BinaryFormatter (); MemoryStream MS = new MemoryStream (); Bf. Serialize (MS, CookieValue ); Byte [] result = new byte [ms. Length]; Result = ms. ToArray (); String temp = System. Convert. ToBase64String (result ); Ms. Flush (); Ms. Close (); Return temp; } # Endregion # Region obtain Cookie /// <Summary> /// Obtain the Cookie /// </Summary> /// <Param name = "CookieName"> Cookie name </param> /// <Returns> Cookie value </returns> Public static object GetCookie (string CookieName) { HttpCookie myCookie = new HttpCookie (CookieName ); MyCookie = HttpContext. Current. Request. Cookies [CookieName]; If (myCookie! = Null) Return ConvertStringToObject (myCookie. Value ); Else Return null; } Private static object ConvertStringToObject (string value) { Byte [] B = System. Convert. FromBase64String (value ); MemoryStream MS = new MemoryStream (B, 0, B. Length ); BinaryFormatter bf = new BinaryFormatter (); Return bf. Deserialize (MS ); } # Endregion # Region clear Cookie /// <Summary> /// Clear Cookie /// </Summary> /// <Param name = "CookieName"> Cookie name </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 ); } # Endregion } } |