Server-side Cookie Helper Methods


/ Published in: VB.NET
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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 Function ReadCookie(ByVal cookieName As String) As String
  9. Return If(Not Me.Request.Cookies(cookieName) Is Nothing, Me.Server.HtmlEncode(Me.Request.Cookies(cookieName).Value).Trim(), String.Empty)
  10. End Function
  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. Protected Sub WriteCookie(ByVal cookieName As String, ByVal cookieValue As String, ByVal isHttpCookie As Boolean)
  18. Dim aCookie As New HttpCookie(cookieName) With {.Value = cookieValue, .Expires = DateTime.Now.AddDays(1), .HttpOnly = isHttpCookie}
  19. Me.Response.Cookies.Add(aCookie)
  20. End Sub
  21.  
  22. ''' <summary>
  23. ''' Writes a cookie.
  24. ''' </summary>
  25. ''' <param name="cookieName">Name of the cookie.</param>
  26. ''' <param name="cookieValue">The cookie value.</param>
  27. Protected Sub WriteCookie(ByVal cookieName As String, ByVal cookieValue As String, ByVal isHttpCookie As Boolean, ByVal cookieExpireDate As DateTime)
  28. Dim aCookie As New HttpCookie(cookieName) With {.Value = cookieValue, .Expires = cookieExpireDate, .HttpOnly = isHttpCookie}
  29. Me.Response.Cookies.Add(aCookie)
  30. End Sub
  31.  
  32. ''' <summary>
  33. ''' Deletes a single cookie.
  34. ''' </summary>
  35. ''' <param name="cookieName">Name of the cookie.</param>
  36. Protected Sub DeleteCookie(ByVal cookieName As String)
  37. Dim aCookie As New HttpCookie(cookieName) With {.Expires = Date.Now.AddDays(-1)}
  38. Response.Cookies.Add(aCookie)
  39. End Sub
  40.  
  41. ''' <summary>
  42. ''' Deletes all the cookies available to the application.
  43. ''' </summary>
  44. ''' <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>
  45. Protected Sub DeleteAllCookies()
  46. Dim i As Integer
  47. For i = 0 To Me.Request.Cookies.Count - 1
  48. Me.Response.Cookies.Add(New HttpCookie(Me.Request.Cookies(i).Name) With {.Expires = DateTime.Now.AddDays(-1)})
  49. Next
  50. End Sub
  51.  
  52. #End Region

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.