Question

I'm currently checking a older piece of C# code used to maintain a login session.

public static ZRWebserviceSession CurrentSession { get { return _currSession; } set { _currSession = value; } }
private static ZRWebserviceSession _currSession;


public static bool IsSessionActive()
{
    if (_currentSession == null || !_currentSession.IsOpen || !_currentSession.IsLoggedIn) {
         return false;
    }
    return true;
}

I was always told using globals is bad practice and I'm looking for ways to improve this bit of code by at least getting rid of the static field used to maintain the session.

The current situation is as follows:

When the application starts the session object is initiated with a server address (taken from a config file) it should connect to. The object then retrieves the session data (token etc.) from the server to store within itself and it is then assigned to the static variable for access through the entire application. This is only done at the start of the application run or when the user explicitly restarts the session.

While a session is active other pieces of code can then call methods on the session object to retrieve the session data and make calls to the connected webservice.

Can this be improved? Is using globals still a bad practice if used for sessions or something akin to that?

EDIT: To clarify what kind of application this is: This isn't a web application but a client application that connects to a webservice. ZRWebserviceSession is a library object that represents a login session for the user currently using the client application. Kind of like the the session object of the Fabebook SDK https://developers.facebook.com/docs/reference/ios/current/class/FBSession/.

Was it helpful?

Solution

Never store sessions in a static variable!

Static variable means that when another user logs in, the static variable will be updated it with the new session and the first user will work under the last user's session. Never user static varible in a web application.

The only case where i use static variables is with constants(which are static by default);

Update:

Well a good use of static variable with session could be that when the user logs in, save the user object in session and then do this:

    var user = GetUser('username','password');

    if(user == null){
      throw new NullReferenceException("user does not exists! login failed");
   }

    else{
    Session["currentuser"] = user;

    }

So now you can do this:

public class Globals{

  public static User GetCurrentUser()
  {
     return (User)System.Web.HttpSessionStateBase["currentuser"];
  }
}

So that when you need the current user information you just call Globals.GetCurrentUser().

Licensed under: CC-BY-SA with attribution
scroll top