ASP.NET Cookies
Posted
by Aamir Hasan
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by Aamir Hasan
Published on Tue, 30 Mar 2010 05:04:00 GMT
Indexed on
2010/03/30
5:13 UTC
Read the original article
Hit count: 794
Cookies are domain specific and cannot be used across different network domains. The only domain that can read a cookie is the domain that sets it. It does not matter what domain name you set.
Cookies are used to store small pieces of information on a client machine. A cookie can store only up to 4 KB of information. Generally cookies are used to store data which user types frequently such as user id and password to login to a site.
The HttpCookie class defined in the System.Web namespace represents a browser cookie.
Creating cookies (C#)
Dim cookie As HttpCookie = New HttpCookie("UID")
cookie.Value = "id"
cookie.Expires = #3/30/2010#
Response.Cookies.Add(cookie)
cookie = New HttpCookie("username")
cookie.Value = "username"
cookie.Expires = #3/31/2010#
Response.Cookies.Add(cookie)
Creating cookies (VB.NET)
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
Creating cookies (C#)
HttpCookie MyCookie = new HttpCookie("Background");
MyCookie.Value = "value";
Response.Cookies.Add(MyCookie);
Reading cookies (VB.NET)
Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
' Read and add all cookies to the list box
For Each str In cookieCols
ListBox1.Items.Add("Value:" Request.Cookies(str).Value)
Next
Reading cookies (C#)
ArrayList colCookies = new ArrayList();
for (int i = 0; i < Request.Cookies.Count; i++)
colCookies.Add(Request.Cookies[i]);
grdCookies.DataSource = colCookies;
grdCookies.DataBind();
Deleting cookies (VB.NET)
Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
' Read and add all cookies to the list box
Request.Cookies.Remove("PASS")
Request.Cookies.Remove("UID")
Deleting cookies (C#)
string[] cookies = Request.Cookies.AllKeys;
foreach (string cookie in cookies)
{
ListBox1.Items.Add("Deleting " + cookie);
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
© ASP.net Weblogs or respective owner