在 ASP.NET 中从数据库添加会话变量的最佳方法是什么?
在我的 asp.net MVC 应用程序中,我想添加一个变量(用户所拥有的系统类型的标志),每当页面加载或用户执行某些操作时都可以访问该变量。我决定为此添加一个会话变量(这看起来合理吗?),我只需要从数据库中的表中获取标志即可。我的计划是在 Session_Start 上设置变量,但这似乎不是正确的方法,因为我需要查询数据库,并且我不确定是否应该从 Global.asax 进行设置。我应该在哪里填充这个变量?或者有更好的方法吗?
提前致谢!
In my asp.net MVC application, I want to add a variable (a flag for the kind of system a user has) that can be accessed whenever a page loads or the user performs certain actions. I have decided to add a session variable for this (does this seem reasonable?), and I just need to grab the flag from a table in the database. My plan was to set the variable on Session_Start, but this doesn't appear to be the right way to do it as I need to query the database and I'm not sure if I should from the Global.asax. Where should I be populating this variable? Or is there a better way to do it?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Session 变量是一个合理的选择,session_start 可以是获取该值的地方。但是,如果该值是特定于用户的,那么在这种情况下,您需要用户身份。身份验证将建立用户的身份,而不是会话启动(两者在 ASP.NET 中都是独立的) - 因此,更好的选择是
Application_AcquireRequestState
,而不是session_start
,您应该在其中检查用户是否是是否已通过身份验证,如果是,则检查您的会话变量是否已设置。如果没有设置,那么您可以从数据库中获取值。一个细微的变化是按需加载,即创建一个包装方法来获取标志值。包装方法将检查值是否已被检索 - 如果没有,那么它将获取它并将该值缓存在适当的存储中(例如会话状态)。
Session variable is a reasonable choice and session_start can be a place to get the value. However, if the value is user specific then in such case, you need user identity. Authentication will establish user's identity and not session start (both are independent in ASP.NET) - so instead of
session_start
, better bet would beApplication_AcquireRequestState
where you should check if user is authenticated or not and if yes, then check if your session variable has been set or not. If not set then you can get the value from database.A slight variation would be on-demand loading i.e. create a wrapper method to get the flag value. Wrapper method will check if value has already been retrieved or not - if not then it will fetch it and cache the value in suitable store (e.g. session state).