When i implement the following code in my Global.asax.cs in the session timeout procedure, It prompts me an error...

HttpContext.Current.Response.Redirect("login.aspx");

What will be the problem?

Note: I want to forward the user to login page when the session is timeout.So i used this. Correct me if i am wrong in my procedure.

Dani AI

Generated

Short answer: the NullReferenceException happens because Session_End runs outside any HTTP request — there’s no HttpContext/Response to call Redirect on. was right: Session_End is for server-side cleanup (and only fires for InProc sessions), not for sending the browser anywhere.

A practical server-side pattern is to detect an expired session on the next request and redirect then. Put this in Global.asax (AcquireRequestState) or a base page so it runs only for page requests, not for images/CSS/AJAX. The detection trick: if the session is new but the request contains an ASP.NET session cookie, the previous session expired. Example:

void Application_AcquireRequestState(object sender, EventArgs e)
{
    var ctx = HttpContext.Current;
    if (ctx == null || ctx.Session == null) return;

    // skip login page and AJAX/static requests
    if (ctx.Request.Url.AbsolutePath.EndsWith("/login.aspx", StringComparison.OrdinalIgnoreCase)) return;
    if (ctx.Request.Headers["X-Requested-With"] == "XMLHttpRequest") return;

    if (ctx.Session.IsNewSession && ctx.Request.Cookies["ASP.NET_SessionId"] != null)
    {
        ctx.Response.Redirect("~/login.aspx");
    }
}

If you prefer to keep logic closer to pages, use a BasePage that checks a session token (for example Session["UserId"]) on OnInit and redirects when it’s missing but the user should be authenticated.

A better UX is proactive client-side handling: emit the session timeout from server (minutes) to the page and use JavaScript to warn or redirect after inactivity, or keep the session alive with periodic pings. Example:

<script>
var timeoutMs = 2 * 60 * 1000; // match server Session.Timeout in minutes
var t = setTimeout(function(){ window.location = '/login.aspx'; }, timeoutMs);
document.addEventListener('mousemove', function(){ clearTimeout(t); t = setTimeout(function(){ window.location = '/login.aspx'; }, timeoutMs); });
</script>

Do not call Response.Redirect from Session_End. Use Session_End only for server cleanup (logging, releasing resources). Test for AJAX and static requests, exclude the login page to avoid redirect loops, and choose a server- or client-side approach that best fits your app.

Recommended Answers

All 4 Replies

Please elaborate on "prompts me an error"--I presume this was an unhandled exception... post the type of exception and the actual text of the message.

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Session.Timeout = 2;

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.
            HttpContext.Current.Response.Redirect("login.aspx",true);

        }

these are my code

And it provides NullReferenceException was hanndled by user code and it provides this exception on ";" at session_end event...

Sorry for late reply...

Can u help me out????

If I remember correctly, the session end event doesn't have an HTTP context because it's not initiated by a request; it happens on the server when it decides the session is over, either timed out or abandoned.

So How can i implement it gusano79... Because I am a newbie to web apps development.Can you give me a clear explanation please?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.