What is cookie in asp.net?

How to create Cookie in asp.net?

What is the use of Cookie?

How to use Cookie in asp.net?

Description about Cookie is bellow:

Cookie is a small file.Cookie is used to identify a user.
Ata time same computer send requests a page with a browser, it will send the cookie too. With ASP,
you can both create and retrieve cookie values.

How to create Cookie?

We can create Cookie using with “Response.Cookies” command.
Note:- The Response.Cookies command must appear BEFORE the <html> tag.

Below example, we will create a cookie named “Name”
and assign the value “Peter”


<%
Response.Cookies("Name")="Peter"
%>

We can also make a properties to a cookie,
like setting a date when the cookie should expire:



<%
Response.Cookies("Name")="Peter"
Response.Cookies("Name").Expires=#May 10,2012#
%>

How to Retrieve a Cookie Value?

We can retrieve a cookie value using “Request.Cookies” command.
Below example, we retrieve the value of the cookie named “firstname” and display it on a page:



<%
fname=Request.Cookies("Name")
response.write("Firstname=" & fname)
%>

Output:Firstname=Peter

Cookie with Keys

When the cookie contains a collection of multiple values, we say that the cookie has Keys
In the example below, we will create a cookie collection named “user”.
The “user” cookie has Keys that contains information about a user:

<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

Read all Cookies

Follow the below code:



<%
Response.Cookies("Name")="peter"
Response.Cookies("user")("firstname")="Peter"
Response.Cookies("user")("lastname")="Alex"
Response.Cookies("user")("country")="India"
Response.Cookies("user")("age")="30"
%>

If you want to read all the cookies sent to a user.

Note:-That the code below checks if a cookie has Keys with the HasKeys property

Follow the below code:



<!DOCTYPE html>
<html>
<body>

<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br>")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br>")
end if
response.write "</p>"
next
%>

</body>
</html>
Output:-

firstname=Peter

user:firstname=Peter
user:lastname=Alex
user:country=India
user:age=30

About the Author

avatar