Here I will explain how to create and read cookie values in asp.net using c#.
By using Response.Cookies and Request.Cookies properties we can create and read cookie values in asp.net using c#.
Default.aspx
Add this html in your aspx page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Write and Read Cookies in Asp.net using C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:button id="btnWrite" runat="server" text="Write Cookies" onclick="btnWrite_Click" />
<asp:button id="btnRead" runat="server" text="Read Cookie Values" onclick="btnRead_Click" />
<br />
<asp:label id="lblResult" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
Add this namespaces and code in code behind file :
using System;
using System.Web;
protected void btnWrite_Click(object sender, EventArgs e)
{
Response.Cookies["UserId"].Value = "123";
Response.Cookies["UserId"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["UserName"].Value = "Nikhil Sangani";
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
lblResult.Text = "Cookie Values Created Successfully";
}
protected void btnRead_Click(object sender, EventArgs e)
{
string userid = Request.Cookies["UserId"].Value;
string username = Request.Cookies["UserName"].Value;
lblResult.Text = "<b>Cookie Values</b> : UserId: " + userid + ", UserName: " + username;
}
By using Response.Cookies and Request.Cookies properties we can create and read cookie values in asp.net using c#.
Default.aspx
Add this html in your aspx page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Write and Read Cookies in Asp.net using C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:button id="btnWrite" runat="server" text="Write Cookies" onclick="btnWrite_Click" />
<asp:button id="btnRead" runat="server" text="Read Cookie Values" onclick="btnRead_Click" />
<br />
<asp:label id="lblResult" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
Add this namespaces and code in code behind file :
using System;
using System.Web;
protected void btnWrite_Click(object sender, EventArgs e)
{
Response.Cookies["UserId"].Value = "123";
Response.Cookies["UserId"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["UserName"].Value = "Nikhil Sangani";
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
lblResult.Text = "Cookie Values Created Successfully";
}
protected void btnRead_Click(object sender, EventArgs e)
{
string userid = Request.Cookies["UserId"].Value;
string username = Request.Cookies["UserName"].Value;
lblResult.Text = "<b>Cookie Values</b> : UserId: " + userid + ", UserName: " + username;
}
Comments
Post a Comment