在 ASP.Net 中包装会话状态的首选方法是什么?
我有一个使用会话状态的 ASP.Net 项目,我想对访问会话状态的方式更加严格,我对代码中浮动的所有字符串不满意。我还需要知道何时在会话状态中存储/更新特定值以跟踪该对象的最新值。
使用常量很容易解决字符串问题,但它对跟踪没有帮助。将它们全部封装在一个类中很有吸引力,但是我必须将会话对象传递给该类,这似乎有点混乱
我正在考虑使用以下两个选项之一:
- 会话对象上的扩展 getters 和 setters
- 扩展会话对象上的方法返回带有 getter 和 setter 的类
第一个给出了语法:
var thing = Session.GetThing();
Session.SetThing(thing);
第二个给出了:
var thing = Session.Wrapper().Thing;
Session.Wrapper().Thing = thing;
两者都有其吸引力,尽管我倾向于第二个。在理想的世界中,我希望能够做到这一点:
var thing = Session.Thing(); // easy to do
Session.Thing() = thing; // don't think it's possible
处理这个问题的首选方式是什么?这些,另一种方式,还是我只是做错了?
I've got an ASP.Net project that uses session state, I'd like to be a little more strict about how we access session state, I'm not happy about all the strings floating around the code. I also need to know when a particular value is stored/updated in session state for tracking that object's latest value.
The string issue is easy to solve using constants, but it doesn't help with the tracking. Encapsulating them all in a single class is appealing, but then I have to pass the session object to that class, and that seems a little messy
I'm thinking of using one of two options:
- Extension getters and setters on the session object
- An extension method on the session object to return a class with the getters and setters
The first gives me the syntax:
var thing = Session.GetThing();
Session.SetThing(thing);
The second gives:
var thing = Session.Wrapper().Thing;
Session.Wrapper().Thing = thing;
Both have their appeal, though I'm leaning towards the second. In an ideal world I'd like to be able to do this:
var thing = Session.Thing(); // easy to do
Session.Thing() = thing; // don't think it's possible
What's the preferred way of handling this? Any of these, another way, or am I just doing it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的首选方法是将所有需要访问的变量放入一个对象中。然后我在页面的基类中放置一个变量,该变量提供对会话中对象的适当访问。真正执行此操作的唯一方法是提供一个标准,要求使用该对象,然后进行代码/同行评审,以确保各种字符串/变量不会最终堵塞会话。
My preferred method is to put all of the variables that need access into an object. Then I put a variable in our page's base class that provides the appropriate access to the object in the session. The only manner of true enforcement of this is to provide a standard that requires usage of this object and then code/peer review to ensure that miscellaneous strings/variables don't end up clogging the session up.
您不必将 Session 传递给每个类,您可以:
我相信,这是典型的方法。 HttpContext 具有
当前
静态可用的属性。You don't have to pass the Session to each class, you can have:
This, I believe, is the typical approach. HttpContext has the
Current
property which is statically available.