开发者

asp.net mvc - where to store userid - integer?

开发者 https://www.devze.com 2022-12-20 16:48 出处:网络
I got the vibe using session variable is sort of开发者_开发问答 looked down upon in ASP.NET MVC.

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


Sessions are meant to be used for stateful user interaction - a shopping cart comes to mind. They are looked down upon because they are painful to test and tend to force serialization logic into the controller. If you just want to minimize queries, you should use caching.

EDIT: Tutorials for HttpContext.Cache are surprisingly hard to come by. Steven Sanderson has ~4 Pages in Pro ASP.net MVC Framework (Apress 2009) p. 530-534.

Caching in asp.net-mvc might give you some hints too.


Session state. Shouldn't use it when it's not appropriate. But nothing else quite works for credentials. Just make sure they are serializable, so that you can push session out of process when you need to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号