Using Cookies in ASP.NET

0 replies
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<cookies.Count;n++)

{

HttpCookie cookie = cookies[n];

Response.Write("<hr/>Name: <b>" + cookie.Name + "</b><br />");

Response.Write("Expiry: " + cookie.Expires + "<br />");

Response.Write("Address1: " + cookie.Address1+ "<br />");

Response.Write("Address2: " + cookie.Address2+ "<br />");

Response.Write("City: " + cookie.City+ "<br />");

Response.Write("Zip: " + cookie.Zip+ "<br />");

}




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" %>


shrnmlss6
#aspnet #cookies

Trending Topics