COOKIES IN ASP.NET C# VERSION

By Peter A. Bromberg, Ph.D.

Peter Bromberg  

For some reason we seemed to have a terrible time figuring out how to do cookies in ASP.NET. If you look at some of the sample code on the Web, I truly believe it is possible to become thoroughly confused!



Cookies in ASP.NET - at least the basic kind - are no more difficult than in Classic ASP or in Client-side Javascript. Here is a sample ASPX page you can try (set the expiration days to a negative number to erase the cookie), and below appears the source for the page:

 

<%@ Page Language="C#" EnableSessionState="false" %>
<HTML>
<HEAD>
<script runat="server" ID=Script1>
string cookyexpires="";
void SubmitButton_Click(Object Src, EventArgs E) {
msg.Text =SetCookie(cookname.Text, cookvalue.Text, Convert.ToInt32(cookexpiry.Text)).ToString();
msg.Text+=". Expires: " + Response.Cookies[cookname.Text].Expires.ToString();
}
void SubmitButton_Click2(Object Src, EventArgs E) {
msg.Text =GetCookie(cookname.Text);
}
public bool SetCookie(string cookiename, string cookievalue ,int iDaysToExpire)
{
try{
HttpCookie objCookie = new HttpCookie(cookiename);
Response.Cookies.Clear();
Response.Cookies.Add(objCookie);
objCookie.Values.Add(cookiename,cookievalue);
DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire);
Response.Cookies[cookiename].Expires =dtExpiry;
}
catch( Exception e){
return false;
}
return true;
}
public string GetCookie(string cookiename){
string cookyval="";
try{
cookyval= Request.Cookies[cookiename].Value;
}
catch(Exception e){
cookyval="";
}
return cookyval;
}
</script>
</HEAD>
<BODY>
<BASEFONT FACE=VERDANA>
<CENTER><h1>Cookies in ASP .NET - C# Version</h1></CENTER>
<Form runat="server">
<asp:TextBox type="text" id=cookname runat="server" />Cookie Name<BR>
<asp:TextBox type="text" id=cookvalue runat="server" />Cookie value<BR>
<asp:TextBox type="text" id=cookexpiry runat="server" />Days to Expiration<BR>
<asp:Button id="submitbutton" text="Set cookie" OnClick="SubmitButton_Click" runat="server"/>
<asp:Button id="submitbutton2" text="Get cookie" OnClick="SubmitButton_Click2" runat="server"/>
</form>
<asp:Label id="msg" runat="server" /><BR>
<asp:Label id="stat" runat="server" />
</BODY>



Peter Bromberg is an independent consultant specializing in distributed .NET solutionsa Senior Programmer /Analyst at in Orlando and a co-developer of the EggheadCafe.com developer website. He can be reached at pbromberg@yahoo.com

Do you have a question or comment about this article? Have a programming problem you need to solve? Post it at eggheadcafe.com forums and receive immediate email notification of responses.