-->

01 March 2020

Asp.Net Cookies

  Asp.Net CS By Example       01 March 2020

 Asp.Net Cookies 

 In this article we are leanin about ASP.NET Cookies. If We want to store data related to a particular user, we could use the Session object, but this approach has an important drawback: its contents are lost when the user closes the browser window.To store user data for longer periods of time, we need to use cookies.

 Cookies are small files that are created in the web browser’s memory or on the client’s hard disk. The maximum size of a cookie file is 4 KB.We can create two types of cookies. Transient Cookie (memory) and Persistent Cookie (hard disk). Transient Cookies are accessible till the time the browser is running. Persistent Cookies are cookies which have an expiry time. When we don't set expiry time for the cookie, the cookies are treated as transient cookies.

  In ASP.NET, a cookie is represented by the HttpCookie class. We read the user’s cookies through the Cookies property of the Request object, and we set cookies though the Cookies property of the Response object. Cookies expire by default when the browser window is closed (much like session state), but their points of expiration can be set to dates in the future; in such cases, they become persistent cookies.

 In below Code show how to use cookies in asp.net.

  Code: FrmCookieDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FrmCookieDemo.aspx.cs" 
Inherits="LearnAsp.Net.ControlDemo.ApplicationState.FrmCookieDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblMsg" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

  Code: FrmCookieDemo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnAsp.Net.ControlDemo.ApplicationState
{
    public partial class FrmCookieDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie userCookie;
            userCookie = Request.Cookies["UserID"];
            if (userCookie == null)
            {
                lblMsg.Text =
                "Cookie doesn't exist! Creating a cookie now.";
                userCookie = new HttpCookie("UserID", "Ram");
                userCookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(userCookie);
            }
            else
            {
                lblMsg.Text = "Welcome back, " + userCookie.Value;
            }
        }
    }
}

  Output:
Asp.Net Cookies
logoblog

Thanks for reading Asp.Net Cookies

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.