What is the difference between a Session and a Cookie?

会话与Cookie管理
本文介绍了网站中会话(Session)和Cookie的使用方法。会话用于维护用户状态并存储常用对象,而Cookie则存储在用户计算机上,通常用于简单的用户设置。文章详细解释了两种方式的工作原理和技术细节。

Sessions

Sessions are stored per-user in memory(or an alternative Session-State) on the server. Sessions use a cookie(session key) to tie the user to the session. This means no "sensitive" data is stored in the cookie on the users machine.

Sessions are generally used to maintain state when you navigate through a website. However, they can also be used to hold commonly accessed objects. Only if the Session-state is set to InProc, if set to another Session-State mode the object must also serializable.

Session["userName"]="EvilBoy";if(Session["userName"]!=null) 
  lblUserName.Text=Session["userName"].ToString();

Cookies

Cookies are stored per-user on the users machine. A cookie is usually just a bit of information. Cookies are usually used for simple user settings colours preferences ect. No sensitive information should ever be stored in a cookie.

You can never fully trust that a cookie has not been tampered with by a user or outside source however if security is a big concern and you must use cookies then you can either encrypt your cookies or set them to only be transmitted over SSL. A user can clear there cookies at any time or not allow cookies altogether so you cannot count on them being there just because I user has visited your site in the past.

//add a username CookieResponse.Cookies["userName"].Value="EvilBoy";Response.Cookies["userName"].Expires=DateTime.Now.AddDays(10);//Can Limit a cookie to a certain DomainResponse.Cookies["domain"].Domain="Stackoverflow.com";//request a username cookieif(Request.Cookies["userName"]!=null) 
   lblUserName.Text=Server.HtmlEncode(Request.Cookies["userName"].Value);

sidenote

It is worth mentioning that ASP.NET also supports cookieless state-management

转载于:https://www.cnblogs.com/xiaoshiyilang/archive/2012/06/27/2565801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值