0

I have a project in MVC. I would like to save a variable and have it accessible as long as the user is logged in, to get it or set it.

The reason for this is that the application uses the information I would put in there, to get data. I now need to add admin functions so an admin can see more then only his own results, and therefore I would need to change this ID, depending on what result he wants to see.

I have tried using a session, but the problem I have with that is that when the user closes the website, and at a later time returns, he is still logged in, but the session variable is null.

I also tried to add a property to my base class. I was able to set it, but when I tried to get it in a different controller, the property was null as well.

What is the best/fastest/correct way to do this? I would prefer to not use the database for this, if possible.

Robin
  • 2,704
  • 7
  • 30
  • 47

1 Answers1

0

What you are looking for is a "Session". On login you can just do

Session["Key"] = "Value";

And on logout you can empty the field

Session["Key"] = String.Empty;

You can read more about sessions here: https://msdn.microsoft.com/en-us/library/ms178581.aspx

Maru
  • 894
  • 1
  • 12
  • 29
  • Yes, I have tried that, but when a user disconnects and comes back later, but is still 'logged in' due to cookies, the session is empty, but I only can fill it on login. Is there a way I can force a user to logout then when he closes the website? – Robin Jan 18 '16 at 12:31
  • Yes, you would have to signal the webserver on window close. A different approach would be to signal the server via AJAX every 10 minutes and logout the user after 15 minutes if there was no signal. – Maru Jan 18 '16 at 12:35
  • Also see the following problem for this question: http://stackoverflow.com/questions/6162188/javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-win – Maru Jan 18 '16 at 12:36
  • Thanks, I will look into this! – Robin Jan 18 '16 at 12:39