C# 如何在asp.net中检查会话是否已过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10480110/
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
How to Check whether Session is Expired or not in asp.net
提问by user1379439
I've specified the session timeout in web.config file. When the session is timeout I'm not getting redirect to the login page but I am getting an error saying object reference not set to an instance.
我已经在 web.config 文件中指定了会话超时。当会话超时时,我没有重定向到登录页面,但我收到一条错误消息,指出未将对象引用设置为实例。
Can anyone tell me the solution for this?
谁能告诉我这个问题的解决方案?
采纳答案by Darin Dimitrov
You can check the HttpContext.Current.User.Identity.IsAuthenticatedproperty which will allow you to know whether there's a currently authenticated user or not.
您可以检查HttpContext.Current.User.Identity.IsAuthenticated属性,这将使您知道当前是否有经过身份验证的用户。
回答by Pranay Rana
Edit
编辑
You can use the IsNewSession property to check if the session was created on the request of the page
您可以使用 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");
}
}
}
}
pre
预
Store Useridin session variable when user logs into website and check on your master page or created base page form which other page gets inherits. Then in page load check that Useridis present and not if not then redirect to login page.
Userid当用户登录网站并检查您的母版页或创建的其他页面继承的基页表单时,存储在会话变量中。然后在页面加载检查Userid是否存在,如果不存在则重定向到登录页面。
if(Session["Userid"]==null)
{
//session expire redirect to login page
}
回答by Adil
Check if it is null or not e.g
检查它是否为空,例如
if(Session["mykey"] != null)
{
// Session is not expired
}
else
{
//Session is expired
}
回答by Imran Rizvi
I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.
我不喜欢在代码中检查会话变量,而是使用 FormAuthentication。它们具有内置功能,可以重定向到 web.config 中指定的给定 LoginPage。
However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.
但是,如果您想明确检查会话,您可以检查您之前在会话中创建的任何变量的 NULL 值,正如 Pranay 回答的那样。
You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section
您可以创建 Login.aspx 页面并在那里写下您的消息,当会话过期时 FormAuthentication 自动重定向到 FormAuthentication 部分中给出的 loginUrl
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30">
</forms>
</authentication>
The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.
问题是您不能为 Login 和 SessionExpire 提供单独的页面,因此您必须显示/隐藏 Login.aspx 上的某些部分以双向操作。
There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html
还有另一种方法可以在超时后重定向到 sessionexpire 页面而不更改 formauthentication->loginurl ,请参阅以下链接:http: //www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html
回答by Brian
Use Session.Contents.Count:
使用Session.Contents.Count:
if (Session.Contents.Count == 0)
{
Response.Write(".NET session has Expired");
Response.End();
}
else
{
InitializeControls();
}
The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.
上面的代码假设您至少在用户第一次访问您的网站时创建了一个会话变量。如果您没有,那么您很可能没有为您的应用程序使用数据库。对于您的情况,您可以使用以下示例手动分配会话变量。
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
Best of luck to you!
祝你好运!
回答by equiman
I use the @Adi-lester answer and add some methods.
我使用@Adi-lester 答案并添加了一些方法。
Method to verify if Session is Alive
验证 Session 是否处于活动状态的方法
public static void SessionIsAlive(HttpSessionStateBase Session)
{
if (Session.Contents.Count == 0)
{
Response.Redirect("Timeout.html");
}
else
{
InitializeControls();
}
}
Create session var in Page Load
在页面加载中创建会话变量
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
Create SaveData method (but you can use it in all methods)
创建 SaveData 方法(但您可以在所有方法中使用它)
protected void SaveData()
{
// Verify if Session is Alive
SessionIsAlive(Session);
//Save Data Process
// bla
// bla
// bla
}
回答by Ravi
Here I am checking session values(two values filled in text box on previous page)
在这里我正在检查会话值(在上一页的文本框中填充的两个值)
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();
}
}
回答by Mou
this way many people detect session has expired or not. the below code may help u.
通过这种方式,许多人检测会话是否已过期。下面的代码可以帮助你。
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");
}
}
}
}
}

