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

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

问题描述

什么是会话和一个Cookie的区别?

What is the difference between a Session and a Cookie?

应该使用哪一个什么情况?

What circumstances should each be used?

推荐答案

会话

访问存储每用户内存(或替代的Session-State )在服务器上。会话使用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方式,如果设置为其他会话状态模式对象还必须序列化。

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通常只是一点点信息。 Cookies是通常用于简单的用户设置的颜色preferences等。 否敏感信息都不应当存储在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,然后你可以加密c​​ookie,或者将它们设置为只通过SSL传输。用户可以在任何时间显然有饼干或不允许饼干完全,所以你不能对他们在那里只是因为用户在过去访问您的网站数。

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

旁注

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

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

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

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