Asp.net How To Write a Cookie and Read

Asp.net How To Write a Cookie and Read

How to Read and Write cookie in Asp.net. You can store user specific data at client side using cookies. Here we will see how to Read and write cookies in Asp.net. Do not store sensitive information like password or credit card numbers in cookies. You can store other information cookie like login user name, preferences, font size, user preferred themes etc.

You can maintain the data across the web pages using cookie at client side. When user requests the page, browser sends cookie information related to domain or page for that user.

Asp.net C# write cookie example.

Here we will create cookie named User using Asp.net C#. Http Cookie instance will be passed to response of web page. The instance UserNameCookie holds name and value pair, in our example we are setting name of cookie as “UserName” and Value as “Satalaj”.

C# Cookie example.

protected void Page_Load(object sender, EventArgs e)
{

HttpCookie UserNameCookie = new HttpCookie("UserName");
UserNameCookie.Value = "Satalaj";

Response.Cookies.Add(UserNameCookie);

}

VB.net cookie example.

Protected Sub Page_Load(sender As Object, e As EventArgs)

Dim UserNameCookie As New HttpCookie("UserName")
UserNameCookie.Value = "Satalaj"

Response.Cookies.Add(UserNameCookie)

End Sub

Asp.net Read Cookie Example.

To Read Cookie in Asp.net, access cookie information stored inside request. Let's see example.

C# Read Cookie.

protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.Cookies["UserName"].Value;

Response.Write("Retrived user name from cookie is: " + username);
}

VB.net Read Cookie.

Protected Sub Page_Load(sender As Object, e As EventArgs)

Dim UserNameCookie As New HttpCookie("UserName")
UserNameCookie.Value = "Satalaj"

Response.Cookies.Add(UserNameCookie)

End Sub

Summery: We have used instance of HttpCookie to read and write cookie. To write cookie we have added name and value of cookie to HttpCookie instance and passed to Response. To retrieve value from cookie, we used Request object.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5