js代碼:
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/(^\s+)|\s+$/g, "");
}
var x = 0;
function myRefresh() {
var httpRequest = new ActiveXObject("microsoft.xmlhttp");
httpRequest.open("GET", "sessionout.aspx", false);
httpRequest.send(null);
x++;
if (x < 2) //60次,也就是Session真正的到期時間是30分鐘
{
setTimeout("myRefresh()", 30 * 1000); //30秒
}
}
myRefresh();
window.onbeforeunload = function() //author: meizz
{
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth - 20;
if (b && window.event.clientY < 0 || window.event.altKey) {
$.ajax(
{
type: "Post",
url: "SessionHandler.ashx",
success: function() {
}
})
}
}
</script>
webconfig sessionState設定:
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="1"/>
判斷使用者是否登入:
public static bool UserIsLogin(string userid)
{
bool isLogin = false;
ArrayList list = HttpContext.Current.Application.Get("GLOBAL_USER_LIST") as ArrayList;
if (list == null)
{
list = new ArrayList();
}
if (list.Contains(userid))
{
isLogin = true;
}
else
{
list.Add(userid);
HttpContext.Current.Application.Add("GLOBAL_USER_LIST", list);
}
return isLogin;
}
session 到期或使用者退出時 從ArrayList 移除該使用者:
void Session_End(object sender, EventArgs e)
{
//string url=HttpContext.Current.Request.Url.AbsolutePath.ToString();
//if .IndexOf("SysAdmin") == -1)
//{
string loginLogid = Convert.ToString(Session["loginLogid"]);
if (!string.IsNullOrEmpty(loginLogid))
{
erp_crm.BLL.crm_loginLog BllLoginLog = new erp_crm.BLL.crm_loginLog();
erp_crm.Model.crm_loginLog loginLog = BllLoginLog.GetModel(loginLogid);
loginLog.exitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
BllLoginLog.Update(loginLog);
}
string strUserId = Convert.ToString(Session["userid"]);
ArrayList list = Application.Get("GLOBAL_USER_LIST") as ArrayList;
if (strUserId != null && list != null)
{
list.Remove(strUserId);
Application.Add("GLOBAL_USER_LIST", list);
}
// Response.Redirect("login.aspx");
//}
//在會話結束時啟動並執行代碼。
// 注意: 只有在 Web.config 檔案中的 sessionstate 模式設定為
// InProc 時,才會引發 Session_End 事件。如果會話模式
//設定為 StateServer 或 SQLServer,則不會引發該事件。
}
安全退出: Session.Abandon();
參考:http://www.cnblogs.com/myaspnet/archive/2010/11/03/1867703.html