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

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

问题描述

Session 和 Cookie 有什么区别?

What is the difference between a Session and a Cookie?

应该分别在什么情况下使用?

What circumstances should each be used?

推荐答案

Sessions

会话按用户存储在内存中(或替代会话状态)在服务器上.会话使用 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.

会话通常用于在您浏览网站.但是,它们也可用于保存经常访问的对象.仅当会话状态设置为 InProc 时,如果设置为另一个 Session- 状态模式对象也必须可序列化.

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

Cookie 按用户存储在用户计算机上.cookie 通常只是一些信息.Cookies 通常用于简单的用户设置、颜色偏好等.任何敏感信息都不应存储在 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,那么您可以加密您的 cookie 或将它们设置为仅通过 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["userName"].Domain = "Stackoverflow.com";

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

旁注

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

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

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

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