我在 web.config 文件中指定了会话超时。当会话超时时,我没有重定向到登录页面,但我收到一条错误消息,指出对象引用未设置为实例。
谁能告诉我这个问题的解决方案?
您可以检查该HttpContext.Current.User.Identity.IsAuthenticated
属性,该属性将使您知道当前是否存在经过身份验证的用户。
编辑
您可以使用 IsNewSession 属性检查会话是否是根据页面请求创建的
protected void Page_Load()
{
if (Context.Session != null)
{
if (Session.IsNewSession)
{
string cookieHeader = Request.Headers["Cookie"];
if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
Response.Redirect("sessionTimeout.htm");
}
}
}
}
预
Userid
当用户登录网站并检查您的母版页或创建的其他页面继承的基本页面表单时,存储在会话变量中。然后在页面加载中检查Userid
是否存在,如果不存在则重定向到登录页面。
if(Session["Userid"]==null)
{
//session expire redirect to login page
}
我不想在代码中检查会话变量,而是使用 FormAuthentication。它们具有内置功能,可重定向到 web.config 中指定的给定 LoginPage。
但是,如果您想明确检查会话,您可以检查您之前在会话中创建的任何变量的 NULL 值,正如 Pranay 回答的那样。
您可以创建 Login.aspx 页面并在那里写下您的消息,当会话到期时 FormAuthentication 会自动重定向到 FormAuthentication 部分中给出的 loginUrl
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30">
</forms>
</authentication>
问题是您不能为 Login 和 SessionExpire 提供单独的页面,因此您必须显示/隐藏 Login.aspx 上的某些部分以双向操作。
还有另一种方法可以在超时后重定向到 sessionexpire 页面而不更改 formauthentication->loginurl ,请参阅以下链接:http ://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html
使用Session.Contents.Count
:
if (Session.Contents.Count == 0)
{
Response.Write(".NET session has Expired");
Response.End();
}
else
{
InitializeControls();
}
上面的代码假设您在用户第一次访问您的网站时创建了至少一个会话变量。如果您没有,那么您很可能不会为您的应用程序使用数据库。对于您的情况,您可以使用下面的示例手动分配会话变量。
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
祝你好运!
检查它是否为空,例如
if(Session["mykey"] != null)
{
// Session is not expired
}
else
{
//Session is expired
}
我使用@Adi-lester 答案并添加一些方法。
验证会话是否处于活动状态的方法
public static void SessionIsAlive(HttpSessionStateBase Session)
{
if (Session.Contents.Count == 0)
{
Response.Redirect("Timeout.html");
}
else
{
InitializeControls();
}
}
在页面加载中创建会话变量
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
创建 SaveData 方法(但您可以在所有方法中使用它)
protected void SaveData()
{
// Verify if Session is Alive
SessionIsAlive(Session);
//Save Data Process
// bla
// bla
// bla
}
这样很多人检测会话是否已过期。下面的代码可以帮助你。
protected void Page_Init(object sender, EventArgs e)
{
if (Context.Session != null)
{
if (Session.IsNewSession)
{
HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
if (newSessionIdCookie != null)
{
string newSessionIdCookieValue = newSessionIdCookie.Value;
if (newSessionIdCookieValue != string.Empty)
{
// This means Session was timed Out and New Session was started
Response.Redirect("Login.aspx");
}
}
}
}
}
在这里,我正在检查会话值(在上一页的文本框中填写了两个值)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
{
Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
}
else
{
lblUnit.Text = Session["sessUnit_code"].ToString();
LblGrcSr.Text = Session["sessgrcSerial"].ToString();
}
}