C# 在 Session_end 事件上重定向到另一个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18565791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:36:07  来源:igfitidea点击:

Redirecting to another page on Session_end event

c#asp.net

提问by s.k.paul

I would like to auto-redirect to login page when session time outs.

我想在会话超时时自动重定向到登录页面。

In web.config file, i have the following code

在 web.config 文件中,我有以下代码

<configuration>
    <system.web>
       <sessionState mode="InProc"  timeout="1"/>
    </system.web>
</configuration>

In Global.asax file-

在 Global.asax 文件中 -

protected void Session_End(object sender, EventArgs e)
{
    Response.Redirect("LoginPage.aspx");
}

But after time-out, i am receiving the following error:

但超时后,我收到以下错误:

HttpException was unhandled by user code.

Response is not available in this context.

用户代码未处理 HttpException。

响应在此上下文中不可用。

Any clue to solve this issue?

有什么线索可以解决这个问题吗?

采纳答案by NiKiZe

Session_End is called when the session ends - normally 20 minutes after the last request (for example if browser is inactive or closed).
Since there is no request there is also no response.

Session_End 在会话结束时被调用 - 通常在上次请求后 20 分钟(例如,如果浏览器处于非活动状态或关闭)。
由于没有请求,因此也没有响应。

I would recommend to do redirection in Application_AcquireRequestStateif there is no active session. Remember to avoid loops by checking current url.

Application_AcquireRequestState如果没有活动会话,我建议进行重定向。请记住通过检查当前 url 来避免循环。

Edit:I'm no fan of .Nets built in authentication, Example goes in Global.asax:

编辑:我不喜欢 .Nets 内置身份验证,示例Global.asax如下:

    protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        try
        {
            string lcReqPath = Request.Path.ToLower();

            // Session is not stable in AcquireRequestState - Use Current.Session instead.
            System.Web.SessionState.HttpSessionState curSession = HttpContext.Current.Session;

            // If we do not have a OK Logon (remember Session["LogonOK"] = null; on logout, and set to true on logon.)
            //  and we are not already on loginpage, redirect.

            // note: on missing pages curSession is null, Test this without 'curSession == null || ' and catch exception.
            if (lcReqPath != "/loginpage.aspx" &&
                (curSession == null || curSession["LogonOK"] == null))
            {
                // Redirect nicely
                Context.Server.ClearError();
                Context.Response.AddHeader("Location", "/LoginPage.aspx");
                Context.Response.TrySkipIisCustomErrors = true;
                Context.Response.StatusCode = (int) System.Net.HttpStatusCode.Redirect;
                // End now end the current request so we dont leak.
                Context.Response.Output.Close();
                Context.Response.End();
                return;
            }
        }
        catch (Exception)
        {

            // todo: handle exceptions nicely!
        }
    }

回答by Zerkey

I think you are getting "Response is not available in this context" because the user is not making a request to the server, and therefor you cannot provide it with a response. Try Server.Transfer instead.

我认为您收到“响应在此上下文中不可用”是因为用户没有向服务器发出请求,因此您无法为其提供响应。改为尝试 Server.Transfer。

回答by Husein Roncevic

If you are using something like FormsAuthenticationfor maintaining the security of your application, then this part (that part that you are trying to do) will be done for you. If FormsAuthentication discovers that a user's session has expired it will redirect him or her back to you login page.

如果您正在使用类似的东西FormsAuthentication来维护应用程序的安全性,那么这部分(您正在尝试做的部分)将为您完成。如果 FormsAuthentication 发现用户的会话已过期,它会将他或她重定向回您的登录页面。

Second, don't rely too much on Session_Endbecause it will never triggerif you change session provider from InProcto SQLServeror other out of process provider.

其次,不要过分依赖,Session_End因为如果您将会话提供程序从InProc更改为SQLServer或其他进程外提供程序,它将永远不会触发

回答by R.C

You can use session property IsNewSessionto detect whether it is session timeout or not.

您可以使用会话属性IsNewSession来检测是否是会话超时。

The ASP.NET HttpSessionStateclass has IsNewSession()method that returns trueif a new session was created for this request. The key to detecting a session timeout is to also look for the ASP.NET_SessionIdcookie in the request.

如果为此请求创建了新会话,则ASP.NETHttpSessionState类具有IsNewSession()返回的方法true。检测会话超时的关键是还要ASP.NET_SessionId在请求中查找cookie。

Definitely I too agree that we should put the below code in some so called a custom BasePage, which is used by all pages, to implement this effectively.

我当然也同意我们应该将下面的代码放在一些所谓的自定义 BasePage 中,所有页面都使用它,以有效地实现这一点。

override protected void OnInit(EventArgs e)
  {
       base.OnInit(e);   

if (Context.Session != null)
   {
if (Session.IsNewSession)
    {

     string CookieHeader = Request.Headers["Cookie"];
     if((CookieHeader!=null) && (CookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     {
      // redirect to any page you need to
      Response.Redirect("sessionTimeout.aspx");
     } 
   }
 }
}

check this linkfor more explanations if you want to put the above code in a base page class .

如果您想将上述代码放在基页类中,请查看此链接以获取更多说明。

回答by Derek R

You should use Application_AcquireRequestState You'll find that Application_AuthenticateRequest no longer has a session context (or never had one). In my research into this I cam across this post which solved it for me. Thanks go to Waqas Raja.

您应该使用 Application_AcquireRequestState 您会发现 Application_AuthenticateRequest 不再有会话上下文(或从未有过)。在我对此的研究中,我偶然发现了这篇文章,它为我解决了这个问题。感谢Waqas Raja。

asp.net: where to put code to redirect users without a session to the homepage?

asp.net:在哪里放置代码以在没有会话的情况下将用户重定向到主页?

回答by Surbhi

you can simply do the following in web.config

您可以简单地在 web.config 中执行以下操作

<configuration>
<system.web>
<sessionState mode="InProc"  timeout="1" loginurl="destinationurl"/>
</system.web>
</configuration>

Since, we can't redirect from Session_End as no response/redirect is present there.By using this you will be redirected to destinationurl when session will timeout.Hope this helps.

因为,我们无法从 Session_End 重定向,因为那里没有响应/重定向。通过使用它,当会话超时时,您将被重定向到 destinationurl。希望这会有所帮助。

回答by AVS

The easiest way what I feel is to use Meta information and get the trick working. Consider we have a page WebPage.aspxadd the below code in the the WebPage.aspx.csfile.

我觉得最简单的方法是使用元信息并让技巧发挥作用。考虑我们有一个页面WebPage.aspx,在WebPage.aspx.cs文件中添加以下代码。

private void Page_Load(object sender, System.EventArgs e){      
    Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));      
    if(Session[“IsUserValid”].ToString()==””)              
    Server.Transfer(“Relogin.aspx”);
}

In the above code, The WebPage.aspxis refreshed after 5 seconds once the Session is expired. And in the page load the session is validated, as the session is no more valid. The page is redirected to the Re-Login page. Every post-back to the server will refresh the session and the same will be updated in the Meta information of the WebPage.aspx.

上面代码中,WebPage.aspxSession过期5秒后刷新。并且在页面加载中会话被验证,因为会话不再有效。该页面被重定向到重新登录页面。每次回发到服务器都会刷新会话,并且会在WebPage.aspx.