What are cookies? Using Cookies in ASP.NET

Google+ Pinterest LinkedIn Tumblr +

Cookies are used to store user specific information in form of text strings. When a user visits particular website some user specific information gets stored and this information can be retrieved later when the same website gets visited from same machine and can be sent to server. Cookies are associated with websites instead of individual pages.

Web developers can use cookies to store user preference and renders the customized page on next visit according to user’s interest. There are browser imposed limitations regarding size of cookies and number of cookies per website which can be stored.

In ASP.NET cookies can be created using class HttpCookie in System.Web namespace.

Cookies are added to the Cookies collection of response object, the object which is responsible for keeping information to be rendered to browser. Example for writing and reading cookie

 Create an instance of HttpCookie

Dim mycookie as new HttpCookie(“userid”)

 Set parameters like value and expires

mycookie.Value = “1”

mycookie.Expires = DateTime.Now.AddMonths(1)

 Add to the Cookies collection of response object

Response.Cookies.Add(mycookie)

 We can do same thing by directly setting values for Response.Cookies collection

Response.Cookies (“userid”).value = “1”

Response.Cookies (“userid”).Expires = DateTime.Now.AddMonths(1)

 The above code creates cookie and store it in user’s drive for one month. The following code is used to retrieve a cookie later.

 Request object is used to send cookies information along with the request for page to server.

If Not Requet.Cookies(“userid”) Is Nothing Then

Dim a As String

a= Not Requet.Cookies(“userid”)

End If

Here first we are checking whether cookie exists or not because it can be deleted by user. Cookies won’t work if user has disabled cookies in browser settings.

Happy Coding. 

Share.

About Author

Leave A Reply