Home > other >  Session state being reset on every login
Session state being reset on every login

Time:09-16

I have an MVC application with a simple login page.

After a user has successfully been validated I populate session variables with their details ie -

System.Web.HttpContext.Current.Session["usergroup"] = Convert.ToInt32(userDetails[0]);
System.Web.HttpContext.Current.Session["userid"] = Convert.ToInt32(userDetails[1]);

I have a user class like so -

public class MyUser
    {

        public int usergroup { get; set; }
        public int userid { get; set; }

        public static readonly MyUser Default = new MyUser()
        {
            usergroup = 0,
            userid = 0
        };
    }

After the session varibales have been populated I use these to populate my MyUser variables ie -

MyUser.Default.usergroup = (Int32)System.Web.HttpContext.Current.Session["usergroup"];
MyUser.Default.userid = (Int32)System.Web.HttpContext.Current.Session["userid"];

Logging in and out, switching users works fine my dev laptop.

My issue is I have setup an IIS application on my network on a seperate testing laptop, and logged in on that laptop as User1. (where the url is localhost/MyApp)

Then to test the multiuser functionality, on the dev laptop, I logged in as User2 (where the url is http://{MY.NETWORK.IP}/MyApp).

I was able to login fine as User2 however if I go back to the testing laptop and refresh the screen User2's info is accessible and visible even though I am still logged in as User1!

My session variables are being reset every time a user (regardless of the machine) is logging in, how can I stop this from happening?

I have done a lot of reading, and seen people stopping caching by creating a rule in IIS, however this did nothing for me. Also people talking about using 2 separate browsers however again this 1. did nothing and 2 was not relevant to me as I am on 2 completely separate machines.

CodePudding user response:

A web application is a single application, serving multiple users.

Being a single application means that any static values are shared by all users. So when you change the properties of your public static readonly MyUser Default after a login, all users now see that same user.

If you don't want to do System.Web.HttpContext.Current.Session["usergroup"] all through your code (neither would I), then you might wrap that in some class:

public class MySession
{
   public int Usergroup
   {
      get => (int)System.Web.HttpContext.Current.Session["usergroup"];
      set => System.Web.HttpContext.Current.Session["usergroup"] = value;
   }

   // etc
}

As this doesn't store data in itself, you could even make this a static class.

  • Related