20

In Asp.net WebForms there is an event called Session_End() in global.asax, whenever session is timeout or you call Session.Abandon() this event handler is executed, i need to have similar kind of behavior in asp.net Core, is it possible?

4
  • I think you should rephrase your question. Hard to answer!
    – Thomas
    Jun 26, 2016 at 18:23
  • 1
    Have you tried Session.Clear()?
    – Tratcher
    Jun 26, 2016 at 22:27
  • I need to capture the event when session is automatically timeout, is there any why to capture that event or is there any event at all?
    – Shafqat
    Jun 27, 2016 at 19:07
  • I noticed that the Configure function runs on Startup.cs when a Session is created. I used this method to create a way to use HttpContext in classes: stackoverflow.com/a/50815975/6778726
    – M.R.T
    Jun 13, 2018 at 17:12

2 Answers 2

15

You could clear the session by simply calling:

HttpContext.Session.Clear();

2
  • 5
    This will cause the Session to be empty but not deleted or abandoned.
    – M.R.T
    Jun 13, 2018 at 17:22
  • 3
    Then what if we need to do Abandon in .Net Core 3.1? Mar 17, 2020 at 6:51
6

The docs cover most of this. The session timeout is set like this:

services.AddSession(options =>
{
  options.IdleTimeout = TimeSpan.FromSeconds(10);
});

But since it exists is a cookie, the cookie also has an expiration date. So if IdleTimeout expires, the session expires. If the cookie expires, the session is gone. If the cookie is deleted, the session is gone.

Calling Session.Clear() removes the contents of the session, but keeps the session intact (aka, the cookie isn't deleted) as described in the source.

3
  • in Asp.net WebForms there is something called Seesion_End() in global.asax, whenever session is timeout or you call Session.Abandon() this event handler is executed, i need to have similar kind of behaviour in asp.net Core, is it possible?
    – Shafqat
    Jun 29, 2016 at 19:41
  • So there is no way to programmatically invalidate a session e.g. when the user is using a logout button? What would be the recommended way to invalidate a session apart from setting the idle timeout very low. Also what value can be checked to assure that the timeout actually invalidated the session? It somehow seems that the Session implementation in .net Core is not fully implemented, or I'm missing something here. May 23, 2017 at 11:28
  • @vm370 As mentioned by Tratcher above, the recommended way to invalidate a session from code is to call Session.Clear(). There's some further discussion here: Session Issue 27
    – TallMcPaul
    Aug 24, 2017 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.