Using HttpCookie Class in ASP.NET

The HttpCookie class gets and sets properties of individual cookies and provides methods to store, retrieve, and manage multiple cookies.
  • 2873

You can use Cookie to store information about web site visitors when web server and browser are not connected. Like when visitor comes to the web site you can store information about last visit and retrieve that information when visitor comes next time.

HttpCookie Class


The HttpCookie class gets and sets properties of individual cookies. HttpCookie class is located in System.Web namespace. The HttpCookieCollection class provides methods to store, retrieve, and manage multiple cookies.

In the following example we are going to check for a cookie named "Cookie101" in the HttpRequest object. If the cookie is not found, it is created and added to the HttpResponse object.

Code Snippets

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim sb As New StringBuilder()
        ' Get cookie from current request.
        Dim cookie As HttpCookie
        cookie = Request.Cookies.Get("DateCookieExample")
        ' Check if cookie exists in the current request
        If (cookie Is Nothing) Then
            sb.Append("Cookie dosn't exists! ")
            sb.Append("Creating a cookie now. <br/>")
            ' Create cookie.
            cookie = New HttpCookie("DateCookieExample")
            ' Set value of cookie to current date time.
            cookie.Value = DateTime.Now.ToString()
            ' Set cookie to expire in 10 minutes.
            cookie.Expires = DateTime.Now.AddMinutes(10D)
            ' Insert the cookie in the current HttpResponse.
            Response.Cookies.Add(cookie)
        Else
            sb.Append("Cookie retrieved from client. <br/><br/>")
            sb.Append("Cookie Name: " + cookie.Name + "<br/><br/>")
            sb.Append("Cookie Value: " + cookie.Value + "<br/><br/>")
        End If
        Label1.Text = sb.ToString()
    End Sub
</script>
<
html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>HttpCookie Example</title>
</head>
<
body>
  <form id="form1" runat="server">
    <div style="font-family: Verdana; font-size: small">
      <asp:Label id="Label1" runat="server"></asp:Label>   
    </div>
  </form>
</body>
</
html>

Output

Cookie dosn't exists! Creating a cookie now.

Run the web application again because no cookie is found. When we run it again a cookie created, added to the HttpResponse object and the data about web site visitor is shown as below.

Cookie Data Output

Cookie retrieved from client.

Cookie Name: Cookie101

Cookie Value: 1/27/2011 10:45:24 AM
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.