To create a cookie using ASP.NET, we can follow below approach. In this article, we are going to learn two different ways of creating cookies in ASP.NET.
Introduction
A Cookie is a small amount of text that attached to the requet and response in between browser and the server. This small amount of text can be read by the application whenever user browse the it. Please note that cookie is not a good medium to store the confidential data as it is stored into the user browser.
ASPX page
<asp:Button ID="btnCreate" runat="server" Text="Create Cookie - One way" OnClick="CreateCookie1" />
<asp:Button ID="Button1" runat="server" Text="Create Cookie - Other way" OnClick="CreateCookie2" />
In the above code snippet, we have two buttons that calls CreateCookie1 and CreateCookie2 server side method respectively. Here we are trying to show two different ways to create cookie using ASP.NET. You can use anyone of them.
Code behind
protected void CreateCookie1(object sender, EventArgs e)
{
string cookieValue = "Cookie Value 1 ";
HttpCookie cookie = new HttpCookie("CookieKey1", cookieValue);
Response.Cookies.Add(cookie);
}
protected void CreateCookie2(object sender, EventArgs e)
{
string cookieValue = "Cookie Value 2 ";
Response.Cookies["CookieKey2"].Value = cookieValue;
}
Get hundreds of ASP.NET How to Tips and Tricks.
CreateCookie1 method
In this method, 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.
CreateCookie2 method
In this method, 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.
Output
After running the above url, press F12 (in IE 9) to open the developer tools and then click on Cache > View Cookie Information menu to display the above output.
To learn how to read cookies in ASP.NET, click here.
Thanks. If you like this article, share it to your friends by tweeting or sharing it via facebook, linkedin or other websites.