<%@ Page %>
Using Cookies in ASP.NET
What are cookies?
If you are a ASP developer, you probably already know
what are cookies and how to use them in ASP. Just to recap - Cookies are small files stored on client machine which
contain a piece of information. Cookies are typically used to store personalization information, user's nick name,
his preferences etc. In this short code illustration we will see how
to write and read cookies in ASP.NET.
Cookies - ASP way
You need to use cookies collection of Response and Request object in order to write and
read cookies respectively. Let us quickly see how you created cookies using ASP :
Writing cookies to client - ASP Way
Response.Cookies("username")="Bipin"
Response.Cookies("useraddress")("city")="Mumbai"
Response.Cookies("useraddress")("country")="India"
Reading cookies - ASP Way
myvar=Request.Cookies("username")
myvar1=Request.Cookies("useraddress")("city")
myvar2=Request.Cookies("useraddress")("country")
Cookies - ASP.NET way
ASP.NET provides more user friendly way to manipulate cookies. It has a namespace
called System.Web which provides HttpCookie class. The class has properties matching with
traditional ASP. Let us understand this with examples :
<%@ language="VB"%>
<%@ import namespace="System" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.HttpCookie" %>
<script runat="server">
public sub page_load(sender as object,e as eventargs)
if request.cookies("myname")=null then
dim cookie as HttpCookie
cookie=new HttpCookie("myname")
cookie.value="bipin"
response.appendcookie(cookie)
label1.text="Cookie Written"
else
label1.text="Cookie already exists : "
label1.text=label1.text &
request.cookies("myname").value
end if
end sub
</script>
<asp:label id=label1 text="Cookie Written" runat=server />
Create multiple value cookies
<%@ language="VB"%>
<%@ import namespace="System" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.HttpCookie" %>
<script runat="server">
public sub page_load(sender as object,e as eventargs)
if request.cookies("mychoices")=null then
dim cookie as HttpCookie
cookie=new HttpCookie("mychoices")
cookie.Values.Add("Color","blue")
cookie.Values.Add("Font","Verdana")
response.appendcookie(cookie)
label1.text="Cookie Written"
else
label1.text="Cookie already exists : "
label1.text=label1.text &
request.cookies("mychoices").values("Color")
label1.text=label1.text &
request.cookies("mychoices").values("Font")
end if
end sub
</script>
<asp:label id=label1 text="Cookie Written" runat=server />
Both the example are very straight forward and need no extra explanation.