Updated on Kisan Patel
This tutorial will explain you two different ways to creating cookie in ASP.NET website.
Default.aspx
<asp:Button ID="btnCreate1" runat="server" Text="Create Cookie - 1" OnClick="CreateCookie1" />
Default.aspx.cs
protected void CreateCookie1(object sender, EventArgs e) { string cookieValue = "Cookie Value 1 "; HttpCookie cookie = new HttpCookie("CookieKey1", cookieValue); Response.Cookies.Add(cookie); }
In method 1, we are declaring a string variable with value that we will store into the cookie. Then we are instantiating the HttpCookie
object by passing the cookie name and value to store. At last we are calling the Response.Cookies.Add
method by passing the HttpCookie object to create the cookie into the user browser.
Demo
Default.aspx
<asp:Button ID="btnCreate2" runat="server" Text="Create Cookie - 2" OnClick="CreateCookie2" />
Default.aspx.cs
protected void CreateCookie2(object sender, EventArgs e) { string cookieValue = "Cookie Value 2 "; Response.Cookies["CookieKey2"].Value = cookieValue; }
In method 2, we are declaring a string variable with value to store into the cookie and using the Response.Cookies
collection to set the cookie value by passing the cookie name to create. In this case, we do not need to explicitly call the Add method of the Response.Cookies.