How to create a cookie in asp.net

Create a Cookie
Cookie.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        HttpCookie userCookie = new HttpCookie("UserInfo");
        userCookie["Country"] = "Italy";
        userCookie["City"] = "Rome";
        userCookie["Name"] = "Jones";
        userCookie.Expires = DateTime.Now.AddDays(3);
        Response.Cookies.Add(userCookie);
        
        Label1.Text = "Cookie created successfully!";
        
        HttpCookie cookie = Request.Cookies["UserInfo"];
        
        if (cookie != null) 
        {
            string country = cookie["Country"];
            string city = cookie["City"];
            string name = cookie["Name"];
            
            Label2.Text = "Cookie found and read....<br />";
            Label2.Text += "Name: " + name;
            Label2.Text += "<br />Country: " + country;
            Label2.Text += "<br />City: " + city;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to create a cookie in asp.net</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            How to create a Cookie
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label1"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="Green"
            Font-Size="X-Large"
            />
        <br /><br/>
        <asp:Label
            ID="Label2"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="Navy"
            Font-Italic="true"
            Font-Size="X-Large"
            />
    </div>
    </form>
</body>
</html>
More asp.net examples