| What is a cookie?
Cookie are one of several ways to store data about web site visitors
during the time when web server and browser are not connected. Common
use of cookies is to remember users between visits. Practically, cookie
is a small text file sent by web server and saved by web browser on
client machine.
For example, when visitor comes to your web site you can store
information about last visit and retrieve that information when visitor
comes next time.How to create a cookie in ASP.NET
To write a cookie in ASP.NET we can use a code like this:
[ VB.NET ]
Imports
System.Web
' Use
this line to save a cookie
Response.Cookies("MyCookieName").Value = "MyCookieValue"
' How
long will cookie exist on client hard disk
Response.Cookies("MyCookieName").Expires =
Now.AddDays(1)
' To add
multiple key/value pairs in single cookie
Response.Cookies("VisitorData")("FirstName")
= "Richard"
Response.Cookies("VisitorData")("LastVisit")
= Now.ToString()
[ C# ]
// Add
this on the beginning of your .vb code file
using
System;
// Use
this line when you want to save a cookie
Response.Cookies["MyCookieName"].Value ="MyCookieValue";
// How
long will cookie exist on client hard disk
Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);
// To
add multiple key/value pairs in single cookie
Response.Cookies["VisitorData"]["FirstName"]
= "Richard";
Response.Cookies["VisitorData"]["LastVisit"]
= DateTime.Now.ToString();
How to read a cookie in ASP.NET
To read a cookie value, use this:
[ VB.NET ]
Dim
MyCookieValue As String
' We
need to perform this check first, to avoid null exception
' if
cookie not exists
IfNot Request.Cookies("MyCookieName") Is NothingThen
MyCookieValue =
Request.Cookies("MyCookieName").Value
EndIf
[ C# ]
string
MyCookieValue;
// We
need to perform this check first, to avoid null exception
// if
cookie not exists
if(Request.Cookies["MyCookieName"]
!= null)
MyCookieValue = Request.Cookies["MyCookieName"].Value;
How to delete cookie in ASP.NET
To delete existing cookie we actually just set its expiration time to some time in the past. You can do it with code like this:
[ VB.NET ]
' First
check if cookie exists
If
Not Request.Cookies("MyCookieName")
Is Nothing
Then
' Set its expiration time somewhere in the past
Response.Cookies("MyCookieName").Expires
= Now.AddDays(-1)
End
If
[ C# ]
// First
check if cookie exists
if
(Request.Cookies["MyCookieName"] != null)
{
// Set its expiration time somewhere in the past
Response.Cookies["MyCookieName"].Expires
= DateTime.Now.AddDays(-1);
}
HttpCookie class
HttpCookie class is located in System.Web namespace. You can use
HttpCookie class to create and manipulate cookies instead of using of
Response and Request objects.
HttpCookie class have these properties:
- Domain - Gets or sets domain associated with a cookie. It is often used to limit cookie use to web site sub domain.
- Expires
- Gets or sets time when cookie expires. After that time cookie is
deleted by the browser. The maximum life time for cookie is 365 days.
You can increase expiration time every time when visitor visits your
web site, but if visitor don't comes for more than 365 days, the cookie
will be deleted.
- HasKeys - Returns true if cookie has key
pairs or false if not. Cookies are not limited to only simple data as
strings, but could stores key/values pairs as well.
- HttpOnly
- Gets or sets a true/false value if cookie is accesible by client side
javascript. If value is true, cookie will be accessible only by server
side ASP.NET code.
- Item - Not necessary, it exists only because it is used in old classic ASP.
- Name - A name of a cookie.
- Path
- Similar like Domain property, path is used to limit a cookie scope to
specific URL. For example, to limit using of a cookie to sub folder
www.yourdomain.com/forum you need to set Path property to "/forum".
- Secure - Would cookies will transmit through HTTPS protocol by using SSL (secure socket layer) connection.
- Value - Gets or sets a cookie's value.
- Values - Used to get or set key/value pairs in individual cookie.
You can use HttpCookie class to create a cookie or set cookie's properties, like in this example code:
[ VB.NET ]
Dim
MyGreatCookie As HttpCookie = New HttpCookie("MyCookieName")
MyGreatCookie.Value ="Some cookie value"
MyGreatCookie.Expires
= Now.AddDays(100)
Response.Cookies.Add(MyGreatCookie)
[ C# ]
HttpCookie
MyGreatCookie = new
HttpCookie("MyCookieName");
MyGreatCookie.Value ="Some cookie value";
MyGreatCookie.Expires
= DateTime.Now.AddDays(100);
Response.Cookies.Add(MyGreatCookie);
Web browser limits for cookies
Cookie size is limited to 4096 bytes. It is not much, so cookies are used to store small amounts of data, often just user id.
Also, number of cookies is limited to 20 per website. If you make
new cookie when you already have 20 cookies, browser will delete oldest
one.
Your web site visitor can change browser settings to not accept
cookies. In that case you are not able to save and retrieve data on
this way! Because of this, it is good to check browser settings before
saving a cookie. If your visitor blocked cookies in web browser privacy
settings, you need to decide do you still want to save that data on
some other way (maybe with sessions) or to not save it at all. Anyway,
you application must continue to work normally with any browser privacy
settings. It is better to not store any sensitive or critical data to
cookies. If using of cookies is necessary, you should inform your users
with some message like: "Cookies must be enabled to use this
application".
How to find does web browser accepts cookies
There are two possible cases when your client will not accept cookies:
- Web browser does not support cookies
- Web browser supports cookies, but user disabled that option through a browser's privacy settings.
How to check does visitor's web browser supports cookies
[ VB.NET ]
If
Request.Browser.Cookies Then
' Cookies supported
Else
' Web browser not supports cookies
EndIf
[ C# ]
if
(Request.Browser.Cookies)
{
// Cookies supported
}
else
{
// Web browser not supports cookies
}
How to check if client web browser not saved a cookie because of its privacy settings
Code above will tell you does web browser supports cookie
technology, but your visitor could disable cookies in web browser's
privacy settings. In that case, Request.Browser.Cookies will still
return true but your cookies will not be saved. Only way to check
client's privacy settings is to try to save a cookie on the first page,
and then redirect to second page that will try to read that cookie. You
can eventually use the same page to save and read a cookie when perform
a testing, but you must use Response.Redirect method after saving and
before reading cookies.
Best practices with cookies in ASP.NET
Cookies are just plain text, so usually are not used to store
sensitive informations like passwords without prior encryption. If you
want to enable "Remember me" option on web site it is recommended to
encrypt a password before it is stored in a cookie. Cookies are often
used for data like: when visitor last time loged in, what site color
she likes, to keep referer id if we offer affiliate program etc.
Security issues about cookies in ASP.NET
Because of security reasons, your web application can read only
cookies related to your web domain. You can't read cookies related to
other web sites. Web browser stores cookies from different sites
separately.
Cookie is just a plain text file on client's hard disk so it could
be changed on different ways outside of your application. Because of
that, you need to treat cookie value as potentially dengerous input
like any other input from the visitor, including prevention of cross
site scripting attacks. |