strongly typed sessions in asp.net

巧了我就是萌 提交于 2019-12-03 14:29:09

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.

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.

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

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.

kevinpo

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!