EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

ASP.NET Cookie

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » ASP.NET Tutorial » ASP.NET Cookie

asp.net cookies

Introduction to 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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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.

<%
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.

<%
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.

<%
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.

<%
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.

Adding Parameters to the URL

We can add parameters in the URL below.

<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

<%
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to EduCba web site!</p>")
%>

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”

<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

<%
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. Below is the code for the same.

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”. After executing this, we will get below output:

Output:

When we write it as EduCba User in the text box, it will look like below snippet

create cookie

Now we click on Create Cookie button to create a cookie. Then, it will show us a message as below:

Create button

Now try to retrieve it within the expiry time two minutes and click on the retrieve cookie button.

retrieve 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”.

cookie not found

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 it from 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 –

  1. ASP.NET LinkButton
  2. ImageButton in ASP.NET
  3. ASP.NET Hyperlink
  4. RadioButton in ASP.NET

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
ASP.NET Tutorial
  • ASP.NET Controls
    • ASP.NET Label
    • ASP.NET TextBox
    • Button in ASP.NET
    • ASP.NET CheckBoxList
    • ASP.NET DataList
    • RadioButton in ASP.NET
    • ASP.NET CheckBox
    • ASP.NET Hidden Field
    • ASP.NET LinkButton
    • ImageButton in ASP.NET
    • ASP.NET ListBox
    • Drop Down List in ASP.NET
    • ASP.NET Image
    • ASP.NET MVC ViewBag
    • ASP.NET GridView
    • Calendar in ASP.NET
    • ASP.NET Datagrid
    • ASP.NET Hyperlink
    • Timer in ASP.NET
    • ASP.NET Cookie
    • ASP.NET Session
    • ASP.NET SessionID
    • ASP.NET FileUpload
    • ASP.NET Download File
    • ASP.NET UpdatePanel
    • Authentication in ASP.NET
    • ASP.NET MVC Routing
    • ASP.NET MVC Authentication
    • ASP.NET ViewState
  • Basic
    • What is ASP.NET
    • Features of ASP.NET
    • ASP.NET Versions
    • ASP.NET Framework
    • What is MVVM
    • What is Eclipse IDE?
    • ASP.NET Page Life Cycle
    • ASP.NET Server Controls
    • Caching In ASP.NET
    • Data Binding in ASP.NET
    • What is ASP.Net Web Services
    • ASP.Net Interview Questions
    • Asp.Net MVC Interview Questions
    • AJAX Interview Questions
    • What is LINQ
    • Ajax in ASP.NET
  • ASP.Net Validation
    • ASP.Net Validation Controls
    • ASP.Net CompareValidator
    • ASP.NET RequiredFieldValidator
    • ASP.NET ValidationSummary
    • ASP.NET RegularExpressionValidator
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) Learn More