Posted By

mecha on 10/28/10


Tagged

c# aspnet


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Server-side Cookie Helper Methods


 / Published in: C#
 

You should include these Cookie helpers in your base page class. Enjoy!

  1. #region - Cookies -
  2.  
  3. /// <summary>
  4. /// Reads the cookie.
  5. /// </summary>
  6. /// <param name="cookieName">Name of the cookie.</param>
  7. /// <returns></returns>
  8. public string ReadCookie(string cookieName)
  9. {
  10. HttpCookie httpCookie = Request.Cookies[cookieName];
  11. return httpCookie != null ? Server.HtmlEncode(httpCookie.Value).Trim() : string.Empty;
  12. }
  13.  
  14. /// <summary>
  15. /// Writes a cookie and auto sets the expire date to as current day plus one.
  16. /// </summary>
  17. /// <param name="cookieName">Name of the cookie.</param>
  18. /// <param name="cookieValue">The cookie value.</param>
  19. /// <param name="isHttpCookie">if set to <c>true</c> [is HTTP cookie].</param>
  20. public void WriteCookie(string cookieName, string cookieValue, bool isHttpCookie)
  21. {
  22. var aCookie = new HttpCookie(cookieName)
  23. {Value = cookieValue, Expires = DateTime.Now.AddDays(1), HttpOnly = isHttpCookie};
  24. Response.Cookies.Add(aCookie);
  25. }
  26.  
  27. /// <summary>
  28. /// Writes a cookie.
  29. /// </summary>
  30. /// <param name="cookieName">Name of the cookie.</param>
  31. /// <param name="cookieValue">The cookie value.</param>
  32. /// <param name="isHttpCookie">if set to <c>true</c> [is HTTP cookie].</param>
  33. /// <param name="cookieExpireDate">The cookie expire date.</param>
  34. public void WriteCookie(string cookieName, string cookieValue, bool isHttpCookie, DateTime cookieExpireDate)
  35. {
  36. var aCookie = new HttpCookie(cookieName)
  37. {Value = cookieValue, Expires = cookieExpireDate, HttpOnly = isHttpCookie};
  38. Response.Cookies.Add(aCookie);
  39. }
  40.  
  41. /// <summary>
  42. /// Deletes a single cookie.
  43. /// </summary>
  44. /// <param name="cookieName">Name of the cookie.</param>
  45. public void DeleteCookie(string cookieName)
  46. {
  47. var aCookie = new HttpCookie(cookieName) {Expires = DateTime.Now.AddDays(-1)};
  48. Response.Cookies.Add(aCookie);
  49. }
  50.  
  51. /// <summary>
  52. /// Deletes all the cookies available to the application.
  53. /// </summary>
  54. /// <remarks>The technique creates a new cookie with the same name as the cookie to be deleted, but to set the cookie's expiration to a date earlier than today.</remarks>
  55. public void DeleteAllCookies()
  56. {
  57. for (int i = 0; i <= Request.Cookies.Count - 1; i++)
  58. {
  59. Response.Cookies.Add(new HttpCookie(Request.Cookies[i].Name)
  60. {Expires = DateTime.Now.AddDays(-1)});
  61. }
  62. }
  63.  
  64. #endregion

Report this snippet  

You need to login to post a comment.