0
HttpContext.Current.Response.Redirect("~/default.aspx");

When i use this code in session_end in global.asax error to me:

Object reference not set to an instance of an object.

why?!

C Bauer
  • 5,003
  • 4
  • 33
  • 62
Ali Naeimi
  • 612
  • 8
  • 16
  • possible duplicate of [How to handle session end in global.asax?](http://stackoverflow.com/questions/621744/how-to-handle-session-end-in-global-asax) – Win Jan 09 '15 at 17:56

3 Answers3

1

When the event SessionEnd is raised the Request and then the Response are null.

HttpContext.Current.Response //this is null

This is by design: Session ends not during a request but when the session timeout

It usually (default config) happens 20 minutes after the last request.

Since there is no request there is also no response.

You need to understand better how Asp.net Session State works

Anyway if you want to redirect the user to a page if the Session is expired you can check for one of your variables stored on session:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["YOUR_VAR_NAME"]==null)
    {
        Response.Redirect("~/default.aspx");
    }
}
giammin
  • 18,620
  • 8
  • 71
  • 89
1

Session_end is not an event that gets called by the user of your application, it's something that gets called by the server when a session times out. So when you try to access HttpContext, it is null because there is no HttpContext to access (no user who is currently performing some kind of interaction with your site).

Your attempt to redirect a non-existing HttpContext will always fail no matter what you do.

C Bauer
  • 5,003
  • 4
  • 33
  • 62
  • 3
    It doesn't make sense to redirect in the Session_End because there's nothing to redirect. A Session_End event is when a session times out, there's no user to redirect. This is server-side only. – C Bauer Jan 09 '15 at 17:57
  • Is there any solution for this? – sidhewsar Feb 20 '19 at 08:05
  • @sidhewsar What is your expectation? You cannot redirect a user who no longer has a web browser open to your website – C Bauer Feb 20 '19 at 19:46
0

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

I hope the above information will be helpful

BrennQuin
  • 656
  • 10
  • 19