/ Published in: VB.NET
You should include these Cookie helpers in your base page class. Enjoy!
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#Region "- Cookies -" ''' <summary> ''' Reads the cookie. ''' </summary> ''' <param name="cookieName">Name of the cookie.</param> ''' <returns></returns> Protected Function ReadCookie(ByVal cookieName As String) As String Return If(Not Me.Request.Cookies(cookieName) Is Nothing, Me.Server.HtmlEncode(Me.Request.Cookies(cookieName).Value).Trim(), String.Empty) End Function ''' <summary> ''' Writes a cookie and auto sets the expire date to as current day plus one. ''' </summary> ''' <param name="cookieName">Name of the cookie.</param> ''' <param name="cookieValue">The cookie value.</param> Protected Sub WriteCookie(ByVal cookieName As String, ByVal cookieValue As String, ByVal isHttpCookie As Boolean) Dim aCookie As New HttpCookie(cookieName) With {.Value = cookieValue, .Expires = DateTime.Now.AddDays(1), .HttpOnly = isHttpCookie} Me.Response.Cookies.Add(aCookie) End Sub ''' <summary> ''' Writes a cookie. ''' </summary> ''' <param name="cookieName">Name of the cookie.</param> ''' <param name="cookieValue">The cookie value.</param> Protected Sub WriteCookie(ByVal cookieName As String, ByVal cookieValue As String, ByVal isHttpCookie As Boolean, ByVal cookieExpireDate As DateTime) Dim aCookie As New HttpCookie(cookieName) With {.Value = cookieValue, .Expires = cookieExpireDate, .HttpOnly = isHttpCookie} Me.Response.Cookies.Add(aCookie) End Sub ''' <summary> ''' Deletes a single cookie. ''' </summary> ''' <param name="cookieName">Name of the cookie.</param> Protected Sub DeleteCookie(ByVal cookieName As String) Dim aCookie As New HttpCookie(cookieName) With {.Expires = Date.Now.AddDays(-1)} Response.Cookies.Add(aCookie) End Sub ''' <summary> ''' Deletes all the cookies available to the application. ''' </summary> ''' <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> Protected Sub DeleteAllCookies() Dim i As Integer For i = 0 To Me.Request.Cookies.Count - 1 Me.Response.Cookies.Add(New HttpCookie(Me.Request.Cookies(i).Name) With {.Expires = DateTime.Now.AddDays(-1)}) Next End Sub #End Region