ASP.NET 中的强类型会话

发布于 2024-08-17 04:38:30 字数 1906 浏览 3 评论 0原文

如果这个问题已经被问过,请原谅我。 HttpContext.Current.Session["key"] 返回一个对象,我们必须将其转换为特定的 Type 才能使用它。我正在研究类型化会话的各种实现

http ://www.codeproject.com/KB/aspnet/typedsessionstate.aspx http://weblogs.asp.net/cstewart/archive/ 2008/01/09/强类型会话-in-asp-net.aspx http: //geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx

我觉得如果我们想添加的话,我们需要向 SessionManager 添加更多代码(如果我错了,请纠正我)将对象的新 Type 放入会话中,作为方法或作为单独的包装器。我认为我们可以使用泛型

public static class SessionManager<T> where T:class
 {
  public void SetSession(string key,object objToStore)
  {
   HttpContext.Current.Session[key] = objToStore;
  }

  public T GetSession(string key)
  {
   return HttpContext.Current.Session[key] as T;
  }
    
 }
  • 有什么固有的优势吗 使用

    SessionManager.GetSession("sessionString")

比使用

HttpContext.Current.Session["sessionString"] as ClassType
  • 我也认为这会很好 拥有类似

SessionManager["sessionString"] = objToStoreInSession 的内容, 但发现静态类不能有索引器。还有其他方法可以实现这一目标吗?

  • 我的想法是创建一个 SessionObject 来存储 Type 和对象,然后使用密钥将该对象添加到 Session(使用 SessionManager)。检索时,将所有对象转换为 SessionObject ,获取类型(例如 t)和对象(例如 obj),并将 obj 转换为 t 和返回它。

    public class SessionObject { public Type type {get;set;} public Object obj{get;set;} }

这也不起作用(因为返回签名是相同的,但返回类型会有所不同)。

是否有其他优雅的方式以更类型安全的方式保存/检索会话中的对象

Pardon me if this question has already been asked. HttpContext.Current.Session["key"] returns an object and we would have to cast it to that particular Type before we could use it. I was looking at various implementations of typed sessions

http://www.codeproject.com/KB/aspnet/typedsessionstate.aspx
http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx
http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx

and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type of object into session, either as a method or as a separate wrapper. I thought we could use generics

public static class SessionManager<T> where T:class
 {
  public void SetSession(string key,object objToStore)
  {
   HttpContext.Current.Session[key] = objToStore;
  }

  public T GetSession(string key)
  {
   return HttpContext.Current.Session[key] as T;
  }
    
 }
  • Is there any inherent advantage in
    using

    SessionManager<ClassType>.GetSession("sessionString")

than using

HttpContext.Current.Session["sessionString"] as ClassType
  • I was also thinking it would be nice
    to have something like

SessionManager["sessionString"] = objToStoreInSession,
but found that a static class cannot have an indexer. Is there any other way to achieve this ?

  • My thought was create a SessionObject which would store the Type and the object, then add this object to Session (using a SessionManager), with the key. When retrieving, cast all objects to SessionObject ,get the type (say t) and the Object (say obj) and cast obj as t and return it.

    public class SessionObject { public Type type {get;set;} public Object obj{get;set;} }

this would not work as well (as the return signature would be the same, but the return types will be different).

Is there any other elegant way of saving/retrieving objects in session in a more type safe way

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

计㈡愣 2024-08-24 04:38:30

要以非常干净、可维护且灵活的方式处理 Session,请查看此

For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.

终难遇 2024-08-24 04:38:30

该技术的缺点是使用代码需要知道使用哪些键来存储和检索。这可能很容易出错,因为密钥需要完全正确,否则您将面临存储在错误位置或返回空值的风险。

我实际上使用强类型变体,因为我知道会话中需要什么,因此可以设置包装类以适应。我宁愿在会话类中添加额外的代码,而不必担心其他地方的关键字符串。

A downside of the technique is that consuming code needs to be aware of what keys to use for storage and retrieval. This can be error prone, as the key needs to be exactly correct, or else you risk storing in the wrong place, or getting a null value back.

I actually use the strong-typed variation, since I know what I need to have in the session, and can thus set up the wrapping class to suit. I've rather have the extra code in the session class, and not have to worry about the key strings anywhere else.

屋檐 2024-08-24 04:38:30

您可以简单地为会话对象使用单例模式。这样您就可以从单个复合结构对象对整个会话进行建模。这篇文章引用了我正在谈论的内容,并将 Session 对象作为弱类型对象进行讨论: http://allthingscs.blogspot.com/2011/03/documenting-software-architectural.html

You can simply use a singleton pattern for your session object. That way you can model your entire session from a single composite structure object. This post refers to what I'm talking about and discusses the Session object as a weakly typed object: http://allthingscs.blogspot.com/2011/03/documenting-software-architectural.html

权谋诡计 2024-08-24 04:38:30

实际上,如果您正在寻找类型对象,请将类型放置在方法级别,例如:

public T GetValue<T>(string sessionKey)
{

}

如果会话中有相同的对象,则类级别会更多,但会话可以扩展到多种类型。我不知道我会担心控制会话;我只是让它做它已经做了一段时间的事情,并简单地提供一种以更强类型的方式提取和保存信息的方法(至少对消费者而言)。

是的,索引不起作用;您可以将其创建为实例,并通过以下方式使其静态:

public class SessionManager
{
    private static SessionManager _instance = null;


    public static SessionManager Create()
    {
       if (_instance != null)
           return _instance;

       //Should use a lock when creating the instance
       //create object for _instance

       return _instance;
    }

    public object this[string key] { get { .. } }
}

这就是静态工厂实现,但它还通过内部对会话管理器类的静态引用维护单点联系。 sessionmanager 中的每个方法都可以包装现有的 ASP.NET 会话,或使用您自己的内部存储。

Actually, if you were looking to type objects, place the type at the method level like:

public T GetValue<T>(string sessionKey)
{

}

Class level is more if you have the same object in session, but session can expand to multiple types. I don't know that I would worry about controlling the session; I would just let it do what it's done for a while, and simply provide a means to extract and save information in a more strongly-typed fashion (at least to the consumer).

Yes, indexes wouldn't work; you could create it as an instance instead, and make it static by:

public class SessionManager
{
    private static SessionManager _instance = null;


    public static SessionManager Create()
    {
       if (_instance != null)
           return _instance;

       //Should use a lock when creating the instance
       //create object for _instance

       return _instance;
    }

    public object this[string key] { get { .. } }
}

And so this is the static factory implementation, but it also maintains a single point of contact via a static reference to the session manager class internally. Each method in sessionmanager could wrap the existing ASP.NET session, or use your own internal storage.

油焖大侠 2024-08-24 04:38:30

我发布了关于 StackOverflow 问题的解决方案 为会话值的键名创建一个枚举是一个好主意吗?

我认为它非常灵活,并且包含很少的代码来实现它。它需要 .NET 4.5 才能最流畅,但旧版本仍然可以实现。

它允许:

int myInt = SessionVars.MyInt; 
SessionVars.MyInt = 3;

完全像这样工作:

int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;

I posted a solution on the StackOverflow question is it a good idea to create an enum for the key names of session values?

I think it is really slick and contains very little code to make it happen. It needs .NET 4.5 to be the slickest, but is still possible with older versions.

It allows:

int myInt = SessionVars.MyInt; 
SessionVars.MyInt = 3;

to work exactly like:

int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文