How to Create and Read Cookies

Description

Cookies can be created and read using the Context object.

Discussion

Cookies are a way to store information in your web application. You can store data in cookies using the Context object. Context.Request and Context.Response contain methods for adding cookies and checking to see if a cookie exists.

 Reading a Cookie

To read cookies, you must use the Context.Request object. The Cookies property for Context.Request contains all the cookies for your web application. Using the Context.Request.Cookies.Get method, you can a specific cookie from the Context.Request.Cookies object. For example, suppose you have the following code in an .a5w page:

dim cookieName as c
cookieName = "CustomCookie"
if Context.Request.HasCookie(cookieName) then
    ?"The cookie exists." + crlf()
    ?Context.Request.Cookies.Get(cookieName)
else
    ?"The cookie doesn't exist." + crlf()
end if

The Context.Request.HasCookie method is used to determine whether or not a cookie exists. If the cookie doesn't exist, the message "The cookie doesn't exist" will be printed on the page. If the cookie does exist, however, the message "The cookie exists." along with the cookie's value will be displayed.

If you call Context.Request.Cookies.Get method and the requested cookie doesn't exist, the cookie will be created. Prefer to check for the cookie's existence using the Context.Request.HasCookie method before getting the cookie from the Context.Request.Cookies object.

 Creating a Cookie

To create a cookie, you must use the Context.Response object. You can add cookies by calling the Context.Response.AppendCookie method. Context.Response.AppendCookie takes a System::Web::HttpCookie object as a parameter. System::Web::HttpCookie is a .NET object. The code below demonstrates how to create a new System::Web::HttpCookie .NET object that can be added using the Context.Response.AppendCookie method.

dim newCookie as System::Web::HttpCookie = new System::Web::HttpCookie(cookieName)
newCookie.HttpOnly = .t.
newCookie.Value = "This is the cookie's value."
Context.Response.AppendCookie(newCookie)

Limitations

Web Applications Only

See Also