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.
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: