MVC 5 session and/or caching data

1.3k views Asked by At

I am coding an MVC 5 internet application and when a user logs in, I wish to store the log in details so that I can retrieve these details in any class.

I have done some research, and I can either cache the data, or store this data in a session. Because the data is only set when the user logs in, and is only relevant to the logged in user, I believe that I should use the following code:

Session[key] = data;

What are the disadvantages or using the above code? Is there a timeout for this session data, or does it persist until the user closes the browser and/or logs out?

The other option is to use the following code:

System.Web.HttpRuntime.Cache[key] = data;

Are there any advantages that I should consider when using the above code? I am currently leaning towards using the Session[key] = data, as the data is only relevant to the logged in user, and is not application wide.

Thanks in advance.

2

There are 2 answers

0
Joseph Woodward On

Given the requirements specified in your question I believe your best approach would be to use a session. What you describe is exactly what sessions are perfect for - persisting frequently accessed user specific data across their visiting duration.

Session expire when the user closes their browser, or after a time-out that can be specified by your application.

As for using the session object, referencing the Session object directly from within your controller I would highly recommend you look at using an IoC container such as StructureMap to inject the session into the classes that depend on them (such as controllers or services). This allows you to program against an interface rather than implementation and makes for far more testable and maintainable code.

Here's is a brief example taken from a blog post a wrote about this subject where IUserInformation contains the user's session data:

public class UserDetailController : Controller {

    private readonly IUserInformation userInformation;

    public void ExampleLoginController(IUserInformation userInformation) {
        this.userInformation = userInformation;
    }

    [HttpPost]
    public ActionResult ViewProfile()
    {
        ...
        string emailAddress = this.userInformation.EmailAddress;
        ...
    }
}
1
clement On

Session is per user/session while cache is per application. So if I understand well, cache couln't be used for you, isn't it?

Session expires when user close the session, or you can create a session without the login or the user. You set the maximum time for the session on the web.config. Session close when user close the browser.

If you want to make the session available too after browser closing, you have to mix cookies and session. Cookies are stored into the client's browser and can host the Id of the sesssion but I wouldn't recommand it.