Go to beginner's Guide to ASP. NET cookies

Source: Internet
Author: User
Tags send cookies
Document directory
  • Summary

 

Http://www.codeproject.com/KB/aspnet/Beginners_Cookies.aspx

 

Table of contents
  • Introduction
  • What are cookies?
  • How cookies are started?
  • Advantages of cookies
  • Disadvantages of cookies
  • How to create cookies?
  • How to read data from cookies?
  • What is persistent and Non persistent cookies?
  • How to Make Persistent Cookies?
  • Where does cookies are stored in local hard drive?
  • How to remove a persistent cookies before it's expiration time?
  • How to Control cookies scope?
  • Cookie munging
    • What is Cookie munging?
    • Why we are using cookie munging in ASP. NET?
    • How cookie munging works?
    • How to Implement cookie munging?

  • How to configure cookies in browser?
Introduction

First of all I wowould like to thanks to all of readers who read my previous articles and voted me. wow .. what a great support I have got from you people. again thanks to Sean ewington to start up with a very fantastic idea with beginner's walk for web development article. I have written few articles for beginners. I really feel great when my "Beginner's Guide to view State" article displayed in home page"Editor's Choice"Section. Following are articles that I have written so far for the beginner's

  • Processing ing caching in ASP. NET
  • Beginner's Guide to view State
  • Beginner's Guide to ASP. NET application folder

Cookies, sessions, and application objects are in queue. now, it's time for reading about cookies. I have spend a lots of times to prepared this article. and you will be very surprised to know that introduction part is the last topic which I am writing before posting article. I have read articles, books before writing this article. done some hands on also. hope I have explained this well, and hope you people also like it. please give your suggestion and feedback.

What are cookies?

CookiesAre the small files that are created on the client's system or client browser memory(if temporary). Its use for State management that I have already discuss on my view State article. so we can store small piece of information in a client system and we can use it when we needed. most interesting thing is that its works transparently with the user. it can be easily used any where of you web application. cookies store information in a plain text format. if any web application using cookies, server send cookies and client browser will store it. the browser then returns the cookie to the server at the next time the page is requested. the most common example of using a cookie is to store user information, user preferences, password remember option etc. cookies has have advantages and disadvantages. I Will comes to this points, but first have a look how cookies are started.

How cookies are started?

When client request to the server, server send the cookies into client. The same cookies can be referred for subsequent request. As for example, ifcodeproject.comStores session ID as a cookie, when any client hits first times on the server, server generates the session ID and send it as a cookie to client. [as given in Fig 1.0]

Fig 1.0: initial state of cookie Creation

Now for all other subsequent from the same client it uses the session-id from cookies, just like the picture below:

Fig 1.1: subsequent request for other pages

Browser and web server are responsible for exchange cookies information. for different sites, browser keeps cookies differently. if any pages need information from cookies, when that URL is being hit, first its search for local system for cookies information then its moved to server with that information.

Advantages of cookies

Following are main advantages of using cookies in Web application:

  • It's very simple to use and implement.

  • Browser's taking care send data.

  • For multiple sites cookies, browser automatically arranges them.

Disadvantages Of cookies

Main disadvantages of cookies are:

  • Its store data in a simple text format. So it's not secure at all.

  • There is a size limit of cookies data (4096 bytes/4kb ).

  • Number If cookies also limited. Most browser provides limits of storing cookies is 20. If new cookies came, it will discard the old one. Some of browser support up to 300.

  • We need to configure browser. It will not work on a high security configuration of browser. [I have explained about this in details.]

How to create cookies?

For working with cookies we need to use namespace System.web

Now, have a look, on the code, that how can we create a cookies and add it with Web response. 3

The cookies which has been created will persist, until browser has been closed. We can persist the cookies. But how? Just after few point I have discussed it.

How to read data from cookies?

Now, its times to retrieve data from cookies. OK, before reading cookies, first of all we need to check whether a cookies was found or not. "Its always good practice to check cookie before read it, because is browser is disable cookies.

What is persistent and Non persistent cookies?

We can classified cookies in Two Way,

  • Persistent Cookies

  • Non Persistent Cookies

Persistent Cookies : This can be calledpermanent cookies, Which isstored In clienthard-driveUntil itExpires. Persistent cookies shocould have setexpiration dates.Sometimes its stays until the user deletes the cookie. Persistent cookies are used to collect identifying information about the user from that system. I have discuss about the creation of persistent cookies on"How to Make persist cookies?"Section.

Non Persistent Cookies : This can be calledTemporary Cookies. If there is no expires time defined then the cookie is stored inbrowser memory . The example which I have given already its a non-persistent cookies.

Therefore there is no difference between modifying persistent or non-persistent cookies.Only difference between them are Persistent cookies should have an Expatriation time defined within it.

How to Make Persistent cookies?

I have already given an example of non-persistent cookies, for persistent cookies we need only add to expiry times of cookies. in that given code I have added expire time to 5 days. just check the example.

Collapse | copy code
        //Creting a Cookie Object        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");       //Setting values inside it        _userInfoCookies["UserName"] = "Abhijit";        _userInfoCookies["UserColor"] = "Red";        _userInfoCookies["Expire"] = "5 Days";                //Adding Expire Time of cookies         _userInfoCookies.Expires = DateTime.Now.AddDays(5);                //Adding cookies to current web response        Response.Cookies.Add(_userInfoCookies);

Now, looks the most interesting things that where they are store in hard drive.

Where does cookies are stored in local hard drive?

This is one of the interesting things to find out the cookies in your local drive. First of all, from "Explorer folder option", select, show hidden files and folder.

Fig 1.2: Show Hidden Files and folder settings

Now browse into document & settings of the current user and open the cookies folder. Now looks the picture.

Fig 1.3: Reading cooking info in local system

How to remove a persistent cookies before it's expiration time?

This is also a funny task. If you want to remove some persistent cookies before its expiration date, the only way to replacing the cookies with some before expiration date.

Collapse | copy code
        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");        //Adding Expire Time of cookies before existing cookies time        _userInfoCookies.Expires = DateTime.Now.AddDays(-1);        //Adding cookies to current web response        Response.Cookies.Add(_userInfoCookies);
How to Control cookies scope?

We can controlling the scope of cookies by following way

  • Limiting Cookies to Path 

  • Limiting Cookies Domain 

What is Cookie munging?

By default ASP. NET uses cookies to stores session ID's, but I have already discuss some browser does not support cookies, to over comes this problem, ASP. NET uses"Cookie Munging" To manages session variable with out cookies.

[Though this is also related with session, I am just giving a basic overview. I will explain it in details on my next article which will be on session.]

Why we are using cookie munging in ASP. NET?

There are some specific reason to use cookie munging in ASP. NET

  • Some browser does not support cookies.

  • Sometimes, user disable cookies in browser.

How cookie munging works?

When user request for a page on a server, server encoded the session ID and add it with every href link in page. when user click any links ASP. net decodes that session ID and passes it the page that user requesting. now the requesting page can retrieve any session variable. this all happens automatically, if ASP. net detects that the users browser does not support cookies.

Fig 1.4: Steps of cookie munging

How to Implement cookie munging?

For that we have to make session state to Cookie less.

Collapse | copy code
<sessionState cookieless= "true />

Ooo... now I am stopping here on this topic. I will explain it in details when I write an article of session.

How to configure cookies in browser? 

Now, we can just have a look on how can we configure browser for enabled/disabled cookies. Here I have discussed about settings of IE browser. Click onTool->Internet Option -> Go To Privacy Tab. There you will able to see a scroll bar, with following options

  • Accept all cookies

  • Low

  • Medium

  • Medium High

  • Block all cookies

First option will accepts all cookies and last option will block all cookies. You can get the details of those settings while scrolling the bar.

Summary

There are writing topics to learn with cookies. I have covered a small portion hope this will helps all the beginners to startup. Please give your feedback and suggestion.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.