javascript 如何使用 SessionState 获取剩余的会话超时时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11425183/
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 get the remaining session timeout using SessionState?
提问by user1120260
Is it possible to get the REMAINING session timeout using sessionState in ASP.net
是否可以在 ASP.net 中使用 sessionState 获取剩余会话超时
Here is the sessionState code in my webconfig file.
这是我的 webconfig 文件中的 sessionState 代码。
<sessionState
mode="SQLServer"
allowCustomSqlDatabase="true"
sqlConnectionString="my connection here"
timeout="100">
</sessionState>
Thanks
谢谢
采纳答案by Ashwin Singh
Yes you can use the following code to get the remaining time
是的,您可以使用以下代码获取剩余时间
HttpSessionState session = HttpContext.Current.Session;//Return current sesion
DateTime? sessionStart = session[SessionKeys.SessionStart] as DateTime?;//Convert into DateTime object
if(sessionStart.HasValue)//Check if session has not expired
TimeSpan remaining = sessionStart.Value-DateTime.Now ;//Get the remaining time
回答by JeffreyJ
I know this is an old post but there is no correct answer and I needed this answered.
我知道这是一个旧帖子,但没有正确答案,我需要这个答案。
I have used Ashwin's answer somewhat and made it work!
我已经使用了 Ashwin 的答案并使它起作用了!
You need to create the session["SessionStart"] variable where ever you start your session and begin your session. From there it is pretty straight forward, I am returning seconds as the value so I can use javascript to change the seconds to hh:mm:ss, I have also included a string.format to convert the seconds into hh:mm:ss.
您需要在开始会话和开始会话的地方创建 session["SessionStart"] 变量。从那里开始非常简单,我返回秒作为值,因此我可以使用javascript将秒更改为hh:mm:ss,我还包含了一个string.format将秒转换为hh:mm:ss。
// Get the session in minutes and seconds
HttpSessionState session = HttpContext.Current.Session;//Return current session
DateTime? sessionStart = session["SessionStart"] as DateTime?;//Get DateTime object SessionStart
//Check if session has not expired
if (sessionStart.HasValue)
{
TimeSpan timepassed = DateTime.Now - sessionStart.Value;//Get the time passed since the session was created
int TimeOut = (session.Timeout * 60) - Convert.ToInt32(remaining.TotalSeconds);
int h = (TimeOut / 3600);
int m = ((TimeOut / 60) % 60);
int s = TimeOut % 60;
SessionTimeoutValue.InnerText += TimeOut; // or use the string.format below.
//string.Format("{0}:{1}:{2}",
// h,
// m,
// s);
}