ASP.NET MVC Session vs Global vs Cache

23,882

Solution 1

If you use sessions I would recommend having a session class, so that you only need to specify the string name once in code and this will give you IntelliSence also.

 public static class SessionHandler
{   
    // User Values
    private static string _userID = "UserID";
    private static string _userRole = "UserRole";

    public static string UserID
    {
        get
        {
            if (HttpContext.Current.Session[SessionHandler._userID] == null)
            { return string.Empty; }
            else
            { return HttpContext.Current.Session[SessionHandler._userID].ToString(); }
        }
        set
        { HttpContext.Current.Session[SessionHandler._userID] = value; }

    }

    public static string UserRole
    {
        get
        {
            if (HttpContext.Current.Session[SessionHandler._userRole] == null)
            { return string.Empty; }
            else
            { return HttpContext.Current.Session[SessionHandler._userRole].ToString(); }
        }
        set
        { HttpContext.Current.Session[SessionHandler._userRole] = value; }

    }
}

Solution 2

Sessions haven't changed at all in MVC. The GlobalApplication class in Global.asax still exists, too. Pages exist, also, that you would want to refer to a repository in a controller rather than a page. Adding a property to a base controller class is fine; I do it all the time.

Solution 3

You can create a model binder to encapsulate state.

(See Steve Sanderson's mvc book on his shopping cart implementation)

With the model binder, you have access to the controllerContext - which has the HttpContext.

Share:
23,882
dhara tcrails
Author by

dhara tcrails

I'm otac0n on keybase.

Updated on June 09, 2020

Comments

  • dhara tcrails
    dhara tcrails almost 4 years

    I have an application that was written in vanilla ASP.NET that I would like to port over to ASP.NET MVC.

    I, however, am confused about the right place to persist objects. I need to persist for a couple reasons:

    1. I would like all to have a single database connection, wrapped in a "repository" or "manager" style object.
    2. Each user has a user object that needs to be saved on a per-session basis.

    Normally, I would say that #1 would be saved as a static item in the Globals.asax that can be hit using Global.Repository or similar.

    And I would normally say that #2 should be a property with a session backing store somewhere in the base class of the pages.

    Now the reason I am confused is that I have heard that sessions have changed in MVC, and the Global.asax no longer holds the same class. Also, the concept of pages has been removed, so adding a property to the base class of a controller seems... wrong.

    What say yall?