ASP.NET Kill Session By Id

2020-02-06 05:42发布

问题:

My application has a control of User Permissions, because not all users can access full website. At this moment, all those permissions for an specific user are stored in his session, 'cause It would be a problem for me to search at Database every Post Back.

The problem is that when I remove a permission, user can still access the page, and only when he closes the browser, the update take effect.

Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?

回答1:

"Is there a way to Kill an specific Application Session by the ID, forcing user to Log in again?"

No. You can only access the Session object of the user doing the current request (i.e. yourself), not other users Session objects.

So, you need to store the id of the user somewhere else, for example in a static collection. When the user makes the next request you can check if the id is in the collection, and update the permissions or log out the user.

Another alternative would be to keep the permission objects of all currently logged in users in a static collection as well as in their Session variable. That way you would be able to change the permission object without accessing the Session object of that user.

Using static variables in a web application of course comes with the usual precautions. As multiple threads can access it, the access has to be synchonised. Also, as Alexei Levenkov pointed out, if you have multiple servers you have to keep the data synchonised between the servers.



回答2:

You can write Session.Abandon(); or Session.Clear();

or Session.SessionID[int index];

store the particular user session value in this and then use Session.Abandon(); and Session.Clear();

For killing a particular session try using Session.Remove("key");



回答3:

To remove a particular piece of Session, then use Session.Remove(), like this:

Session.Remove("YourKey");

Note: This removes the value and the key from Session, while you may see people use Session["YourKey"] = null; that will only remove the value, but leave the key. This may or may not be what you want, but just wanted to point out the distinction.