如何阻止基本页面递归检测会话超时

发布于 2024-09-13 08:06:23 字数 2829 浏览 3 评论 0原文

备用标题:如何在会话超时时重定向

最终解决方案:致谢:Robin Day(尽管我测试了 Ben 的解决方案并且它也有效,并且其他两个解决方案也是很好的解决方案)

我摆脱了最初的基本页面。

将其放在 Global.asax 的 Session_Start 中

void Session_Start(object sender, EventArgs e) 
{
    string cookie = Request.Headers["Cookie"];
    // Code that runs when a new session is started
    if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))//&& !Request.QueryString["timeout"].ToString().Equals("yes"))  
    {
        if(Request.QueryString["timeout"] == null || !Request.QueryString["timeout"].ToString().Equals("yes"))
            Response.Redirect("Default.aspx?timeout=yes");
    }
}

将其放在 Defualt.aspx 页面上:

 if (!IsPostBack)
    {
        if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
        {
            Response.Write("<script>" +
               "alert('Your Session has Timedout due to Inactivity');" +
               "location.href='Default.aspx';" +
               "</script>");
        }
    }

即使 Default.aspx 页面上发生超时,该解决方案也能正常工作。


结束解决方案

我有一个检查会话超时的基本页面。 (这就是它的全部作用)。如果会话超时,我想重定向到主页。但是,主页也继承自该基页。

我不确定我是否解释得很好:

第 1 步:我的一个页面加载

第 2 步:它停留了 20 分钟以上(这会导致会话超时)。

步骤 3:我单击导致回发的内容

步骤 4:Basepage 检测到超时并重定向到 default.aspx

步骤 5:加载 default.aspx 时,basepage 检测到仍然存在超时,并再次尝试重定向到默认.aspx。 步骤6:重复步骤5

粗体是不需要的效果...

这是底页代码。

using System;  
using System.Web.UI;   
public class SessionCheck : System.Web.UI.Page  
{   
public SessionCheck()  {}  

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

    if (Context.Session != null)  
         {  
             //check the IsNewSession value, this will tell us if the session has been reset.  
             //IsNewSession will also let us know if the users session has timed out  
             if (Session.IsNewSession)  
             {  
                //now we know it's a new session, so we check to see if a cookie is present  
                 string cookie = Request.Headers["Cookie"];  
                 //now we determine if there is a cookie does it contains what we're looking for 
                 if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
                 {  
                     //since it's a new session but a ASP.Net cookie exist we know  
                     //the session has expired so we need to redirect them  
                     Response.Redirect("Default.aspx?timeout=yes&success=no");  
                 }  
             }  
         }  
     }  
} 

谢谢!!!

(如果您需要进一步说明,请询问)

注意:我知道,如果我重定向到不从此基页继承的页面,则会解决问题。但我不喜欢这个解决方案。

Alternate Title: How to redirect on session timeout

FINAL SOLUTION: Credit to: Robin Day (Although I tested Ben's solution and it also works and the other two solutions are also both good solutions)

I got rid of the basepage that I had originally.

Put this in the Session_Start of Global.asax

void Session_Start(object sender, EventArgs e) 
{
    string cookie = Request.Headers["Cookie"];
    // Code that runs when a new session is started
    if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))//&& !Request.QueryString["timeout"].ToString().Equals("yes"))  
    {
        if(Request.QueryString["timeout"] == null || !Request.QueryString["timeout"].ToString().Equals("yes"))
            Response.Redirect("Default.aspx?timeout=yes");
    }
}

Put this on the Defualt.aspx page:

 if (!IsPostBack)
    {
        if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
        {
            Response.Write("<script>" +
               "alert('Your Session has Timedout due to Inactivity');" +
               "location.href='Default.aspx';" +
               "</script>");
        }
    }

This solution works even when the timeout occurs on the Default.aspx page


END SOLUTION

I have a base page that checks for session timeout. (thats all it does). I want to redirect to the home page if there is a session timeout. However, the home page also inherits from this base page.

I'm not sure if i'm explaining this well:

Step 1: One of my pages loads

Step 2: It sits for more than 20 minutes(this would cause session timeout).

Step 3: I click on something that causes poastback

Step 4: Basepage detects timeout and redirects to default.aspx

Step 5: As default.aspx loads, the basepage detects that there is still a timeout and once again tries to redirect to default.aspx.
Step 6: Repeat step 5

The bold is the undesired effect...

This is the basepage code.

using System;  
using System.Web.UI;   
public class SessionCheck : System.Web.UI.Page  
{   
public SessionCheck()  {}  

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

    if (Context.Session != null)  
         {  
             //check the IsNewSession value, this will tell us if the session has been reset.  
             //IsNewSession will also let us know if the users session has timed out  
             if (Session.IsNewSession)  
             {  
                //now we know it's a new session, so we check to see if a cookie is present  
                 string cookie = Request.Headers["Cookie"];  
                 //now we determine if there is a cookie does it contains what we're looking for 
                 if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
                 {  
                     //since it's a new session but a ASP.Net cookie exist we know  
                     //the session has expired so we need to redirect them  
                     Response.Redirect("Default.aspx?timeout=yes&success=no");  
                 }  
             }  
         }  
     }  
} 

Thanks!!!

(If you need further clarification please ask)

Note: I know that if I redirect to a page that does not inherit from this basepage it would fix the problem. But i don't like this solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

黑凤梨 2024-09-20 08:06:23

您可以在 Global.asax 中使用 Session_OnStart 事件吗?

每当新会话开始时,都会触发一次。您可以在那里进行重定向。

但我认为关键是,如果您尚未进入主页,则只能重定向到主页。您只需检查 Request 对象中的 URL 即可完成此操作。

Can you use the event Session_OnStart within the Global.asax?

This will be fired once whenever a new session begins. You can do your redirect in there.

The key I guess though is that you only redirect to the home page if you're not already on it. You can do this by just checking the URL in the Request object.

新雨望断虹 2024-09-20 08:06:23

我们也有类似的情况。我们首先检查是否存在会话超时,并且在该超时范围内,仅当当前页面不是默认登录页面时才进行重定向。

We had similar situation. We first check if the there's Session Timeout and within that we only redirect if current page is not the Default Login page.

情场扛把子 2024-09-20 08:06:23

下面的代码可以解决您现有的代码,但 robin day 建议使用 global.asax 是一个更好的选择。

if (Context.Session != null)  
     {  
         //check the IsNewSession value, this will tell us if the session has been reset.  
         //IsNewSession will also let us know if the users session has timed out  
         if (Session.IsNewSession)  
         {  
            //now we know it's a new session, so we check to see if a cookie is present  
             string cookie = Request.Headers["Cookie"];  
             //now we determine if there is a cookie does it contains what we're looking for 
             if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
             {  
                 //since it's a new session but a ASP.Net cookie exist we know  
                 //the session has expired so we need to redirect them
                 //Only redirect if the current page is NOT Default.aspx
                 if (Request.Path.Substring(Request.Path.LastIndexOf("/")) != "/Default.aspx") 
                 {
                     Response.Redirect("Default.aspx?timeout=yes&success=no");  
                 }
                 else if (Request.QueryString["timeout"] == "yes")
                 {
                     ScriptManager.RegisterStartupScript(this, this.GetType(), "TimeOutScript", "alert('Your session timed out');", true);
                 }
             }  
         }  
     } 

编辑答案以回复下面的评论,因为它比添加更多评论更容易:

我没有为您提供会话超时时重定向的解决方案,您根本无法这样做,会话已超时出去,没有什么可以重定向的。你说“我只是想知道是否有超时”,我给了你一个解决方案。没有真正的方法可以判断用户是否因为会话超时或因为他们打开了浏览器并启动了新会话而点击了页面 x,您只知道不存在现有会话。如果他们访问需要经过身份验证才能查看的页面,那么您可以假设会话已超时,因为他们不应该从头开始访问该页面。但您无法在主页上执行此操作,因为您无法区分在此页面上会话超时的用户和刚刚第一次访问该页面的用户之间的区别。我已经更新了代码,以便对于除 Default.aspx 之外的每个页面,它都会重定向,并且如果由于会话超时而重定向到 Default.aspx,它将弹出一个 javascript 警报。

The below will do the trick with your existing code but robin day's sugestion of using global.asax is a better option.

if (Context.Session != null)  
     {  
         //check the IsNewSession value, this will tell us if the session has been reset.  
         //IsNewSession will also let us know if the users session has timed out  
         if (Session.IsNewSession)  
         {  
            //now we know it's a new session, so we check to see if a cookie is present  
             string cookie = Request.Headers["Cookie"];  
             //now we determine if there is a cookie does it contains what we're looking for 
             if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
             {  
                 //since it's a new session but a ASP.Net cookie exist we know  
                 //the session has expired so we need to redirect them
                 //Only redirect if the current page is NOT Default.aspx
                 if (Request.Path.Substring(Request.Path.LastIndexOf("/")) != "/Default.aspx") 
                 {
                     Response.Redirect("Default.aspx?timeout=yes&success=no");  
                 }
                 else if (Request.QueryString["timeout"] == "yes")
                 {
                     ScriptManager.RegisterStartupScript(this, this.GetType(), "TimeOutScript", "alert('Your session timed out');", true);
                 }
             }  
         }  
     } 

Editing the answer to respond to comments below becuase it is easier than adding more comments:

I did not provide you with a solution to redirect when the session timed out, you simply cannot do that, the session has timed out, there is nothing to redirect. You said "i just wanna know if there was a timeout" and i gave you a solution for that. There is no real way to tell if a user is hitting page x becuase their session has timed out or because they have opened a browser and started a new session, all you know is there is no existing session. If they hit a page they need to be authenticated to view then you can assume the session has timed out because they should not be hitting the page from scratch. But you can't do this on the home page becuase you can't tell the difference between a user who's session timed out on this page and a user who is just hitting the page for the first time. I have updated the code so that for every page other than Default.aspx it will redirect, and if it has redirected to Default.aspx due to a session time out it will pop up a javascript alert.

栩栩如生 2024-09-20 08:06:23

创建一个公共基本页面,其中包含您希望在主页和其他页面中拥有的所有内容。

然后继承您的主页和另一个基页(例如 SessionCheck),在其中放置会话过期逻辑。除了主页之外的所有页面都必须从 SessionCheck 页面继承。

public class BasePage: System.Web.UI.Page //(this contains all things shared between all pages)
public class SessionCheck : BasePage //(your session loginc in this class)
public class Home : BasePage 

Create a common base page that contains all things you want to have both in your home page and in other pages.

Than inherit from this your home page and another base page (say SessionCheck) in which to put your session expiration logic. All your pages but home have than to inherit from SessionCheck page.

public class BasePage: System.Web.UI.Page //(this contains all things shared between all pages)
public class SessionCheck : BasePage //(your session loginc in this class)
public class Home : BasePage 
╭⌒浅淡时光〆 2024-09-20 08:06:23

在您的基本页面中放置一个属性:

public bool IsDefault { get; set; }

在默认页面的 PreInit 事件中:

public void Default_PreInit(object sender, System.EventArgs e)
{
    this.IsDefault = true;
}

修改您的会话检查:

if (Context.Session != null && !this.IsDefault)
{
    // blibbitty blah blah
}

Put a property in your base page:

public bool IsDefault { get; set; }

In the PreInit event of your default page:

public void Default_PreInit(object sender, System.EventArgs e)
{
    this.IsDefault = true;
}

Modify your session check:

if (Context.Session != null && !this.IsDefault)
{
    // blibbitty blah blah
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文