I got the vibe using session variable is sort of looked down upon in ASP.NET MVC.
Once a user logs in, I would like to retain the user's userId so that I do not have to query it all the time etc.
What is the most efficient way to do that in ASP.NET MVC?
I have seen similar questions pop up once in a while and I can't figure out where this "vibe" is coming from. This is what Session is specifically designed for - for storing session-related information. There's absolutely nothing wrong with using Session to store a user id or similar information.
You got the right vibe. It is just not necessary in many scenarios. Session state can be easily lost and is often misused for handling logged in user (setting that user is logged in is done by setting Session["IsLoggedIn"] = true or by checking Session["User"] != null, suddenly Session disappears and user is logged out), when forms authentication should be used. Here you can read about forms authentication and storing additional data with it:
Forms Authentication Configuration and Advanced Topics
If you still want to use session, it is good to create wrapper to make it more testable and get rid of strings in code:
Wrapper for ASP.NET Session
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With