1

I am trying to redirect user to another page when session ends.

This code will result "Object reference not set to an instance of an object." exception

void Session_End(Object sender, EventArgs E)
{
    HttpContext.Current.Response.Redirect("/");
}

any idea how to do it ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
David Munsa
  • 885
  • 1
  • 16
  • 30
  • When you get that trigger, you do not have any contact with the user page and so the Reponse is null. Try to make some kind of javascript call to check if the user is not loose their session. Its tricky tho, because each call can trigger again the session update. – Aristos Jan 02 '15 at 20:32
  • You're hooking into an event that has nothing to do with a page request, which is why your HttpContext.Current is (likely) the null reference here. What specifically do you want? Do you want to implement a logout function, or possibly detect when a user is outside of a session? Those are each different situations with different answers, each of which being different from the code above. – Anthony Pegram Jan 02 '15 at 20:33
  • http://stackoverflow.com/questions/4453365/session-end-in-global-asax-cs-not-firing-using-forms-authentication ...check like forum – Enrique YC Jan 02 '15 at 20:36
  • i want to redirect the user to the logout page – David Munsa Jan 02 '15 at 20:37
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jan 02 '15 at 20:38
  • @JohnSaunders I'm pretty sure that this Null reference is pretty different from the duplicated question. You can't fix the null reference in this case !!! – mybirthname Jan 02 '15 at 20:45
  • Fixed with another duplicate that answers the question. – Patrick Hofman Jan 02 '15 at 20:50

1 Answers1

1

Session_End is fired internally by the server, based on an internal timer. Because of that, there is no HttpRequest associated when that happens. That is why Response.Redirect or Server.Transfer does not make sense and will not work.

I see in the past workarounds about this but never tried, you should make Base class which every page inherit. OnInit in the base class add this. Base Class inherit UI.Page. If you don't use base class logic you should add this logic to every page which is not nice.

    protected override void OnInit(System.EventArgs e)
    {
         Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));      

         if(Session.IsNewSession)  
            Response.Redirect(“Logout.aspx”);// or another page which you want.
    }

The page should be refreshed after 5 seconds once the Session is expired, with the if you will catch that the session is new and you will redirect.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
mybirthname
  • 17,949
  • 3
  • 31
  • 55