会话和Cookie之间有什么区别? [英] What is the difference between a Session and a Cookie?

查看:272
本文介绍了会话和Cookie之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会话和Cookie之间有什么区别?

What is the difference between a Session and a Cookie?

每种情况下应该使用什么情况?

What circumstances should each be used?

推荐答案

会话

会话存储在每个用户的内存中(或替代会话状态)。会话使用Cookie(会话密钥)将用户绑定到会话。这意味着没有敏感数据存储在用户计算机上的cookie中。

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.

会话< a>通常用于在您浏览网站时保持状态。但是,它们也可以用于保存常用的对象。 仅当会话状态设置为InProc时,如果设置为其他会话状态模式对象还必须可序列化。

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();

Cookie

Cookie 存储在用户计算机上的每个用户。 Cookie通常只是一些信息。 Cookie通常用于简单的用户设置颜色偏好等。 不要将任何敏感信息存储在Cookie中。

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.

您不能完全信任Cookie未被用户篡改,外部源,但如果安全是一个大问题,您必须使用cookie,那么您可以加密您的cookies或设置它们只通过SSL传输。用户可以随时清除其Cookie,或者完全不允许使用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 his cookies at any time or not allow cookies altogether so you cannot count on them being there just because a user has visited your site in the past.

//add a username Cookie
Response.Cookies["userName"].Value = "EvilBoy";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(10);
//Can Limit a cookie to a certain Domain
Response.Cookies["domain"].Domain = "Stackoverflow.com";

//request a username cookie
if(Request.Cookies["userName"] != null)
   lblUserName.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

sidenote

sidenote

值得一提的是,ASP.NET还支持 cookieless 状态-management

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

这篇关于会话和Cookie之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆