Social Icons

Friday, 28 June 2013

Asp.Net Cookies Overview

Introduction:

In my previous articles i explained Client - Side State management techniques like How to use ViewState in Asp.Net, How to Use Hidden Field  in Asp.Net, beginners tutorial to understand QueryString Concept in Asp.Net and Various Examples on Asp.Net and WPF.

         Now we will Purpose of Cookies in Asp.Net, different ways to Create Cookie, How to read Cookie values,How to set Expiration date for Cookie, How to store multiple values in Cookie and Advantages and Disadvantages of Cookies.

Description:

It is one of Client - Side state management techniques in Asp.Net. It is a small text file stored in the client machine and sent by webserver.

             Generally cookies are used to store information like User Visiting pages, User Preferences,authentication , Shopping Cart Details and etc.

Using Cookies:

Different Approaches for Creating/Writing Cookies:

Approach1: 

we will use HttpCookie Class to create Cookie like below

Approach 2:

we can directly add cookie to Response Object like below

Approach 3:Storing Multiple Values in Single Cookie:

Reading Values from Cookies:

Approach1: Reading Single Valued Cookie by using Index 


  Approach2 : Reading Multi Valued Cookies by using Index and by Names of Sub Keys.

If a cookie contains any sub cookies we can access them by using their names only.

Approach 3: Reading Multi Valued Cookies By using name of Cookie and Names of Sub Keys.

  Deleting Cookies:

In the above you saw the code for creating and reading cookies, now see for deleting cookie

 

How to identify whether browser will accept cookies or not:

Request.Browser.Cookies Property will return true if client browser accepts the Cookies.

  HttpCookie class Properties:

HttpCookie class has some important properties 
  • Name: It Contains name of the cookie.
  • Path: Contains the Virtual path of the Cookie.
  • HasKeys: It Contains True if Cookie has Sub Keys.
  • Domain: Contains the Domain Name of the Cookie.
  • Expires:  Contains Expiration Time of Cookie.
  • Secure: It contains true if the cookie needs to pass in secured connection only.

Advantages of using Cookies:

  • Simplicity.Cookie is Light weight, text based structure with simple key-value pairs.
  • No Server Resource required.
  • Configurable expiration. Cookie can be expired based on time set by developers.

Disadvantages of using Cookies:

  • Size limitation of 4 KB. Storing huge information is not possible.
  • User can disable browser Cookies.
  • Total 20 Cookies can be used on a single website. If exceed older cookies will deleted.
  • As it is a text file it can easily tampered. 

Conclusion:

I hope this information about Cookies will give Overview on Cookies in Asp.Net. 

Related Tutorials

No comments:

Post a comment

Please Give your Valuable Suggestions,Questions and Comments to improve my blog.