How to Redirect on Session End [duplicate]

风流意气都作罢 提交于 2019-12-13 02:33:46

问题


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 ?


回答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.



来源:https://stackoverflow.com/questions/27748120/how-to-redirect-on-session-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!