Your Ad Here

Posted By

mecha on 10/28/10


Tagged

aspnet c#


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. protected string ReadCookie(string cookieName) {
  9. return (this.Request.Cookies[cookieName] != null) ? this.Server.HtmlEncode(this.Request.Cookies[cookieName].Value).Trim() : string.Empty;
  10. }
  11.  
  12. /// <summary>
  13. /// Writes a cookie and auto sets the expire date to as current day plus one.
  14. /// </summary>
  15. /// <param name="cookieName">Name of the cookie.</param>
  16. /// <param name="cookieValue">The cookie value.</param>
  17. /// <param name="isHttpCookie">if set to <c>true</c> [is HTTP cookie].</param>
  18. protected void WriteCookie(string cookieName, string cookieValue, bool isHttpCookie) {
  19. HttpCookie aCookie = new HttpCookie(cookieName) {Value = cookieValue, Expires = DateTime.Now.AddDays(1), HttpOnly = isHttpCookie};
  20. this.Response.Cookies.Add(aCookie);
  21. }
  22.  
  23. /// <summary>
  24. /// Writes a cookie.
  25. /// </summary>
  26. /// <param name="cookieName">Name of the cookie.</param>
  27. /// <param name="cookieValue">The cookie value.</param>
  28. /// <param name="isHttpCookie">if set to <c>true</c> [is HTTP cookie].</param>
  29. /// <param name="cookieExpireDate">The cookie expire date.</param>
  30. protected void WriteCookie(string cookieName, string cookieValue, bool isHttpCookie, DateTime cookieExpireDate) {
  31. HttpCookie aCookie = new HttpCookie(cookieName) {Value = cookieValue, Expires = cookieExpireDate, HttpOnly = isHttpCookie};
  32. this.Response.Cookies.Add(aCookie);
  33. }
  34.  
  35. /// <summary>
  36. /// Deletes a single cookie.
  37. /// </summary>
  38. /// <param name="cookieName">Name of the cookie.</param>
  39. protected void DeleteCookie(string cookieName) {
  40. HttpCookie aCookie = new HttpCookie(cookieName) {Expires = System.DateTime.Now.AddDays(-1)};
  41. Response.Cookies.Add(aCookie);
  42. }
  43.  
  44. /// <summary>
  45. /// Deletes all the cookies available to the application.
  46. /// </summary>
  47. /// <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>
  48. protected void DeleteAllCookies() {
  49. for (var i = 0; i <= this.Request.Cookies.Count - 1; i++) {
  50. this.Response.Cookies.Add(new HttpCookie(this.Request.Cookies[i].Name) {Expires = DateTime.Now.AddDays(-1)});
  51. }
  52. }
  53.  
  54. #endregion

Report this snippet  

You need to login to post a comment.