views:

161

answers:

4

when I build asp.net applications that require user login, I write a method in my businees class that returns a Member object instance if the user is logged in, null if not. Then I do this:

Session["User"] = user;

Then in every page load I have to implement this:

User user = Session["User"] as User;
if(null==user){
 //toggle the state of ascx, to show username/password boxes again,
 //Response.Redirect("somewhere else") etc...
}

This looks like its working, but is this a good approach? Because sometimes the Session does not return that object anymore. It happens before 20mins, which is default timeout for session. Is there any reson for that? It happens randomly, when I make several postbacks during testing.

Thanks in advance.

+3  A: 

You cannot use Viewstate - it's scope is the current page. Why don't you use Forms Authentication? It does all this for you, and more, including persisting of the user accounts in the database.

cdonner
+3  A: 

You should use Form Authenticacion, without any doubt. Here are some links of interest:

eKek0
+2  A: 

The best way to store user information in my experience is in the database. Microsoft makes this easy with the SqlMembershipProvider. It gives you a pre-defined schema, with best practices like storing the passwords hashed and with a salt (NOT IN CLEARTEXT!). It's a good start and is customizable. Cheers!

LWoodyiii
A: 

If you're using the default InProc session state, it's only stored in RAM, so it can go away not only when the session times out, but also if the AppPool recycles, which can happen for a number of reasons (idle timeouts, once daily, excessive memory use, etc). In addition, session state is locked by each page, so if your app tries to do multiple accesses at once, you can run into issues.

How large is your User object? If it's not too huge, you might consider storing the data in a cookie, rather than in session state. Silverlight isolated storage is another option. Otherwise, you can keep it the DB and do your own cache management. That can be much more efficient than using the Session dictionary....

I should add that if you can use the built-in Membership provider, it does simplify some of this stuff, but I'm assuming you have your reasons for not going that route--it's definitely not a one-size-fits-all type solution.

RickNZ