C# 会话超时后自动重定向到登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11742699/
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-09 19:02:27  来源:igfitidea点击:

Auto redirect to login after session timeout

c#asp.netredirectloginsession-timeout

提问by Inbal

I am trying to redirect automatically to my login page after session times out. I tried to add this code in my Main.Master page (all the other pages are connected to this master page):

我试图在会话超时后自动重定向到我的登录页面。我尝试在 Main.Master 页面中添加此代码(所有其他页面都连接到此母版页面):

protected void Page_Load(object sender, EventArgs e)
{
            //Redirects to Login Page 3 seconds before session timeout
            Response.AppendHeader("Redirect", Convert.ToString((Session.Timeout * 60) - 3) + "; URL=~/Login.aspx");
}

I configured the session timeout to 1 minute in my web config:

我在我的网络配置中将会话超时配置为 1 分钟:

<sessionState mode="InProc" cookieless="false" timeout="1"/>

but nothing happens

但什么也没发生

Can anyone help me find the problem with this code, or has other ideas how to make it work?

任何人都可以帮我找到这段代码的问题,或者有其他想法如何使它工作?

Edit: Authentication node from web.config

编辑:来自 web.config 的身份验证节点

<authentication mode="Forms">
    <forms name=".CAuthenticated" loginUrl="Login.aspx" protection="All" 
    timeout="20"/>
</authentication>

采纳答案by Peter Ritchie

AppendHeaderis documented as causing an exception if "header is appended after the HTTP headers have been sent" You need to make sure AppendHeader is called before the HTTP headers have been sent. Depending on your master page, the Loadevent might be too late. You could try the Initevent instead.

AppendHeader如果“在发送 HTTP 标头后附加标头”,则记录为导致异常。您需要确保在发送 HTTP 标头之前调用 AppendHeader。根据您的母版页,Load事件可能为时已晚。你可以试试这个Init活动。

回答by D Stanley

I think you need to use Refreshinstead of `Redirect' in your header:

我认为您需要Refresh在标题中使用而不是“重定向”:

Response.AppendHeader("Refresh",
    Convert.ToString((Session.Timeout * 60) - 3) +
    ";URL=~/Login.aspx");

回答by Chris Knight

Here is an example I have that works for me:

这是我有一个对我有用的例子:

    <authentication mode="Forms">
      <forms loginUrl="~/Login/Index" defaultUrl="~/Admin" timeout="20">
      </forms>
    </authentication>

If you have this, there is no need for you to check the timeout cookie yourself. This is assuming you are using Forms Authentication.

如果你有这个,你就不需要自己检查超时 cookie。这是假设您正在使用表单身份验证。

回答by Chris Knight

protected void Page_Init(object sender, EventArgs e)
{
    if (Session["Username"] == null)
    {
        Response.Redirect(ResolveClientUrl("~/login.aspx") + "?returnURL=" + HttpContext.Current.Request.Url.AbsolutePath);
    }
    else
    {
        lblUsername.Text = Session["Username"].ToString();
    }
}