tkalve
tkalve

Reputation: 3196

How can I store user information in MVC between requests

I have an MVC2-site using Windows authentication.

When the user requests a page I pull some user information from the database. The class I retrieve is a Person class.

How can get this from the database when the user enters the site, and pick up the same class without touching the db on all subsequent page requests?

I must admit, I am pretty lost when it comes to session handling in ASP.net MVC.

Upvotes: 0

Views: 1398

Answers (4)

sdcoder
sdcoder

Reputation: 496

HttpContext.Current.Session[key];

Upvotes: 0

Mahesh Velaga
Mahesh Velaga

Reputation: 21981

First of all, if you are using a load balanced environment, I wouldn't recommend any solution that you try without storing it in a database, because it will eventually fail.

If you are not in a load balancing environment, you can use TempData to store your object and then retrieve it in the subsequent request.

Upvotes: 0

Scott
Scott

Reputation: 17257

One option is to retrieve the Person object from your database on the first hit and store it in System.Web.HttpContext.Current.Cache, this will allow extremely fast access and your Person data will be temporarily stored in RAM on the web server.

But be careful: If you are storing significantly large amount of user data in this way, you could eat up a lot of memory. Nevertheless, this will be perfectly fine if you only need to cache a few thousand or so. Clearly, it depends upon how many users you expect to be using your app.

You could add like this:

private void CachePersonData (Person data, string storageKey)
{
    if (HttpContext.Current.Cache[storageKey] == null)
    {
        HttpContext.Current.Cache.Add(storageKey, 
            data, 
            null, 
            Cache.NoAbsoluteExpiration, 
            TimeSpan.FromDays(1), 
            CacheItemPriority.High, 
            null);
    }
}

... and retrieve like this:

// Grab data from the cache 
Person p = HttpContext.Current.Cache[storageKey];

Don't forget that the object returned from the cache could be null, so you should check for this and load from the database as necessary (then cache).

Upvotes: 0

marcind
marcind

Reputation: 53191

You can store that kind of information in HttpContextBase.Session.

Upvotes: 1

Related Questions