articles

Home / DeveloperSection / Articles / Cookies in C#

Cookies in C#

David Miller3955 06-May-2016

This article provides an overview of working with cookies in ASP.NET applications. I will show you the mechanics of working with cookies in ASP.NET. Along the way, I will explain various features and (occasional) oddities of cookies and the support in ASP.NET for them. 

Cookies provide a useful means in Web applications to store user-specific information. For example, when a user visits our site, we can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. 

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site. 

Imagine that when users request a page from your site, www.mindstick.com, your application sends not just a page, but a cookie containing the date and time. When the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk.


Example: below provided a source code for Cookie.

Cookies.aspx file

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Cookies.aspx.cs"Inherits="Session"%>
 
<!DOCTYPEhtml>
 
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title></title>
</head>
<body>
    <formid="form1"runat="server">
        <div>
            <asp:LabelID="lblRecord"runat="server"/><br/>           
            <asp:ButtonID="btnSetCookie"runat="server"Text="SetCookie"OnClick="btnSetCookie_Click"/>
            <asp:ButtonID="btnPrintCookie"runat="server"Text="Print Cookie"OnClick="btnPrintCookie_Click"/> 
        </div>
    </form>
</body>
</html>

 

 

Cookies.aspx.cs file 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
publicpartialclassCookies : System.Web.UI.Page
{
    HttpCookie cook;
    protectedvoid Page_Load(object sender, EventArgs e)
    {
     cook=newHttpCookie("MyCookie");
    }  
    protectedvoid btnSetCookie_Click(object sender, EventArgs e)
    {
        cook.Value = "MyCookie";
    }
    protectedvoid btnPrintCookie_Click(object sender, EventArgs e)
    {
        lblRecord.Text = cook.Name;
    }
} 






Updated 27-Mar-2018

Leave Comment

Comments

Liked By