如何在ASP.NET MVC 4应用程序中使用会话?
我是ASP.NET MVC的新手。我以前用过PHP,创建一个会话并根据当前会话变量选择用户记录是很容易的。
我在互联网上到处寻找一个简单的分步教程,告诉我如何在我的C# ASP.NET MVC 4应用程序中创建和使用会话。我想创建一个带有用户变量的会话,我可以从我的控制器中的任何地方访问这些变量,并且能够在我的LINQ查询中使用这些变量。
-预先感谢!
103
3
尝试
由于网络的无状态特性,会话也是一种非常有用的方式,通过序列化对象并将其存储在会话中,可以跨请求持久化对象。
一个完美的用例是,如果你需要在你的应用程序中访问常规信息,以节省每次请求的额外数据库调用,这些数据可以存储在一个对象中,并在每次请求中不被序列化,像这样。
我们的可重用的、可序列化的对象:
使用情况:
一旦这个对象被序列化,我们就可以在所有的控制器中使用它,而不需要再去创建它或查询数据库中的数据了。
使用依赖注入法注入你的会话对象。
在一个理想的世界里,你会'根据接口编程,而不是实现'并使用你选择的反转控制容器将可序列化的会话对象注入控制器,就像这样(这个例子使用StructureMap,因为它是我最熟悉的)。
然后你将在你的
Global.asax.cs
文件中注册这个对象。对于那些不熟悉注入会话对象的人来说,你可以找到一篇关于这个主题的更深入的博文这里。
警告:
值得注意的是,会话应保持在最低限度,大型会话可能开始导致性能问题。
我们也建议不要在其中存储任何敏感数据(密码等)。
这就是会话状态在ASP.NET和ASP.NET MVC中的工作方式。
ASP.NET会话状态概述 。
基本上,你这样做是为了在Session对象中存储一个值。
要检索该值。