Introduction to ASP.NET Cookie
The following article provides an outline for ASP.NET Cookie. ASP.NET Cookies are a small piece of information that is stored on the client machine. In general, it is used to store the username, telephone number, email id, etc that is user information on the client machine. Cookies are mainly classified in two types is Persistent cookies and Non – persistent cookies. Persistent cookies contain expiry date for its expiration. It will remain on the client machine as it is even after closing the browser. We can set the expiry date to the cookie which determines how long it could stay. Similarly, Non-Persistent cookies don’t have an expiry date. So if we don’t set any expiry property to cookies it is known as a Non-persistent cookie.
Syntax:
Response.Cookies Keyword is a user to create a cookie.
Response.Cookies(userinfo)= 'value'
Userinfo may be the username for which we want to save cookie and value is what we want to pass or save for the userinfo.
How to Create an ASP.NET Cookie?
We can also create cookies as per our convenience. For creating asp.net cookie, we can use “Respone.Cookies” command. This command must appear before the tag <html>.
- We need to create a cookie name first and then need to assign it to the value.
Code:
<%
Response.Cookies("UserName")= "EduCba"
%>
Here its cookies name is “UserNme” and it is assigned value is “EduCba”
- We can set its expiry date by assigning properties to the cookies.
Code:
<%
Response.Cookies("UserName")= "EduCba"
Response.Cookies("UserName").Expires=#March 24,2020#
%>
This cookie will expire on 20 March 2020 as we provide the expiry date in value.
- Let us see how we can retrieve a cookie value. For that, we can use “Request.Cookies” command to retrieve its value.
- We need to retrieve the value of the cookie, which has named as “UserName”, and display it on the page.
Code:
<%
Fname=Request.Cookies("UserName")
Response.write("UserName"= & fname)
%>
- It will give output as “UserName=EduCba”.
- We can also create cookie collection instead of saving and creating a single cookie every time.it is helpful when a cookie has keys it means it has multiple values.
Code:
<%
Response.Cookies("UserName")("firstname")="Educba"
Response.Cookies("UserName ")("lastname")="teams"
Response.Cookies("UserName ")("country")="India"
Response.Cookies("UserName ")("email_ID")="educba.teams@gmail.com”
%>
Therefore, in these ways, we can create cookies in ASP.NET. However, what if your browser is not supporting the cookies. If your application deals with a different browser, which is not supported for the cookies, then we will need to use other ways. We need to pass the information from one page to another via other methods.
It can be done in 2 ways.
1. Adding Parameters to the URL
We can add parameters in the URL below.
Code:
<a href="About-EduCba.asp?fname=EduCba&lname=Teams">Go to About EduCba
Page</a>
It will retrieve the values in the file “About-EduCba.asp” as given below.
Code:
<%
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to EduCba web site!</p>")
%>
2. Using a Form
We can use this method to create. When the user clicks on the submit button ,form passes the user input to “About-EduCba”.
Code:
<form method="post" action="About-EduCba.asp">
First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>
Now retrieve the values in the “About-EduCba.asp” file as given below.
Code:
<%
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to EduCba web site!</p>")
%>
Properties of ASP.NET Cookies
Let us discuss some of the important properties of ASP.NET cookie in detail.
- Domain: It is used to associate the cookies to a particular domain.
- Secure: Cookies are actually insecure things as store the values of a user in the client machine. Therefore, we can set the secure flag so that it enables a secure cookie to only true that is HTTPs by this property. With the help of this property, it will make sure that the cookie has passed via a protected secure channel only.
- Value: With the help of value, we can easily manipulate each cookie.
- Expires: Suppose we want that particular cookies or cookie need not be appearing again after some specific days, then we can set its expiry date as well. If we set the expiry, a date for the cookie will automatically expire and the value stored in the cookies will not appear.
- Values: It is the same as the value property. However, it just deals with the bunch of cookies that can be manipulated with the key or value pair.
- HasKeys: it is mostly applicable for the subkey, if it has a subkey then it will contain True. The default value for haskey is false.
- Name: It represents the name for the key. The default value for the path is server root which is “/”.
- Path: It is a virtual path to submit it with the cookie.
Examples of ASP.NET Cookie
Let us take an example and understand how we can use it. In this example, we will create a cookie and try to retrieve it after the expiration time.
Code:
protected void btncreate_Click(object sender, EventArgs e)
{
Response.Cookies["name"].Value = txtcreatecookie.Text;
Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(2);
Label1.Text = "Cookie has been Created";
txtcreatecookie.Text = "";
}
In the above code, we have set the expiry time as 2 minutes. We have created a cookie and assign textbox values to the name cookie.
Retrieve Cookie Code:
protected void btnretrieve_Click(object sender, EventArgs e)
{
if (Request.Cookies["name"] == null)
{
txtretrieve.Text = "We don’t found any Cookie";
}
else
{
txtretrieve.Text = Request.Cookies["name"].Value;
}
}
When we try to retrieves, the cookie button will check the value is not null. If the value is not null then it will display cookie value in the result. as we have set expiry time as 2 minutes after 2 minutes cookie will get expire and its value will be null. Therefore, after 2 minutes it will show us the output, as “We don’t found any Cookie”.
Output:
When we write it as EduCba User in the text box, it will look like below snippet.
Now we click on Create Cookie button to create a cookie. Then, it will show us a message as below.
Now try to retrieve it within the expiry time two minutes and click on the retrieve cookie button.
Try to retrieve it again after 2 minutes; it will give us a message in the box, as “We don’t found any Cookie”.
Conclusion
We can conclude this article by saying that ASP.NET cookie are important in our day-to-day working life. It saves our efforts of reentering the data, which has already filled up once in the browser by the user. However, just make sure that you will send cookies over a secure channel only to protect them from being passed via unencrypted requests.
Recommended Articles
This is a guide to ASP.NET Cookie. Here we discuss the basic concept and how to create an ASP.NET cookie along with properties in detail. You may also look at the following articles to learn more –