转:Beginner's Guide To ASP.NET Cookies

97 篇文章 0 订阅

 

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

 

Table of Contents 

Introduction

First of all I would 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

Cookies, Session, and Application Object 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 many 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 ?

Cookies  are 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 many 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, if codeproject.com stores session id as a cookies, when any client hits first times on the server, server generates the session id and send it as a cookies to client. [As given in Fig 1.0]

Cookie1.jpg

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:

Cookie2.jpg

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

Cookie3.gif

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

Cookie4.gif

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.

Cookie7.gif

What is Persistent and Non Persistent Cookies ?

We can classified  cookies in two way,

  • Persistent Cookies

  • Non Persistent Cookies

Persistent Cookies : This can be called as permanent cookies, which is stored in client hard-drive until it expires . persistent cookies should have set with expiration 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 called as Temporary Cookies. If there is no expires time  defined then the cookie is  stored in browser 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.

Cookie8.jpg

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.

Cookie9.jpg

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.

Cookie10.jpg

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 on Tool -> 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

Test.gif

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值