.

Thursday, June 19, 2008

Use Cookies in ASP.NET

Using Cookies in ASP.NET



A cookie is stored on the client's machine by their web browser software. To set a cookie, we include information in an HttpResponse that instructs the browser to save a cookie on the client's system. Here's the basic code for writing a Cookie in ASP.NET

Using System.Web;




Response.Cookies["BackgroundColor"].Value = "Red";




And to read the cookie back :

Response.Write


(Request.Cookies["BackgroundColor"].Value);




Note that for security reasons you can only read a cookie that was set within the same domain name.

Sometimes you may need a collection of stored items, such as user address details. In this case you could read in a cookie collection like this:

HttpCookieCollection cookies = Request.Cookies;


for(int n=0;n
{

HttpCookie cookie = cookies[n];

Response.Write("
Name: " + cookie.Name + "
");

Response.Write("Expiry: " + cookie.Expires + "
");

Response.Write("Address1: " + cookie.Address1+ "
");

Response.Write("Address2: " + cookie.Address2+ "
");

Response.Write("City: " + cookie.City+ "
");

Response.Write("Zip: " + cookie.Zip+ "
");

}




Finally, you can see details of cookies during development, by turning on tracing in ASP.NET. Within the @Page directive at the start of the page simply add Trace="true" :

<%@ Page trace="true" language="c#" Codebehind="page.aspx.cs" Inherits="MyPage" %>



No comments:

.