简体   繁体   中英

custom session_end redirect implementation?

I'm working within an MVC app. I have a requirement that when the session ends, the app should redirect to the homepage. I need to implement this logic generically.

I did some research and it looks like 1 requirement is that I need to set anything to session in Session_Start in global.asax. Then Session_End in global.asax should get triggered when the session expires. On session end I need to ensure:

  1. User gets redirected to the Login page. I can redirect to the base url in Session_End to accomplish this.
  2. When the user logs back in s/he should be redirected to the page that he was on when the session expired

What would be the best way for me to accomplish #1 and #2 above?

    protected void Session_Start(object sender, EventArgs e)
    {
        Session["X"] = 1;
    }

    protected void Session_End(object sender, EventArgs e)
    {

    }

A redirect can only be issued in an HTTP response (it is a response header, typically a 302 status). An HTTP response can only be sent in reaction to an HTTP request. So if you want to redirect a browser, you can only do it when they request the next page. When the session_end event occurs, you can't magically reach out the browser and make it do something.

Handling this as a server side event is not the right approach. You will need to add Javascript to the page to keep track of the session time remaining and use location.href instead of using a redirect. For example, for a ten-minute timeout, you could use something like this:

setTimeout(function(){ location.href="https://www.example.com/timeout.aspx"; }, 600000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM