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.

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 cookieName as C = "CustomCookie"
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)

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.GetCookie method], you can get 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.GetCookie(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.

Updating a Cookie 

To create a cookie, you must use the Context.Response object. You can update a cookie using the Context.Response.AppendCookie method. For example:

dim cookieName as c
cookieName = "CustomCookie"
if Context.Request.HasCookie(cookieName) then
    dim cookie as System::Web::HttpCookie = Context.Request.GetCookie(cookieName)
    cookie.HttpOnly = .t.
    cookie.Value = "My new cookie value."
    Context.Response.AppendCookie(cookie)
end if

Limitations

Web Applications Only

See Also