從MSDN和網上大多數資料來看,自動登出時觸發Session_End事件有2中方式,一種是Session.Abandon(),另外一種是關閉所有視窗等待Session的timeout到期。前一種是可靠的,不過需要使用者手動去執行Logout操作,後者則不那麼可靠了,timeout過了基本上就沒動靜了,隨便你怎麼等,有人說是Bug,這個我就沒有深入研究了。
那麼如何?關閉視窗就自動登出呢,這裡有幾個地方要注意。
1、在login的時候用到FormsAuthenticationTicket類,參照MSDN的寫法:
Code
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
strUserID, _
DateTime.Now, _
DateTime.Now.AddMinutes(1), _
True, _
strUserData, _
FormsAuthentication.FormsCookiePath)
' Encrypt the ticket.
Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
' Create the cookie.
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
Response.Redirect(FormsAuthentication.GetRedirectUrl(strUserID, True))
這裏手動將登陸資訊寫入Cookie中,稍微麻煩一點,注意這裡我的timeout時間是1分鐘哈。這樣下次訪問頁面的時候會自動轉到登入視窗,而不管你上次時候成功。
2、建立一個EndSession.aspx頁面,禁用頁面緩衝,並且裡面只有一行代碼Session.Abandon(),這個我就不仔細說了。
3、在你的首頁面或者Master頁面裡面加入以下javascript:
Code
<script language="javascript" type="text/javascript">
function window.onunload()
{
if(event.clientX < 0 && event.clientY < 0) //mouse is out of work space
EndSession();
}
function EndSession()
{
CreatexmlHttpRequest();
xmlHttp.open("GET","<%=Session("ServerBaseURL")%>/Security/EndSession.aspx?Math='" + Math.random() + "'",true);
xmlHttp.send(null);
}
function CreatexmlHttpRequest()
{
xmlHttp=false;
try
{
xmlHttp=new xmlHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.xmlHttp.6.0",
"MSXML2.xmlHttp.5.0",
"MSXML2.xmlHttp.4.0",
"MSXML2.xmlHttp.3.0",
"MSXML2.xmlHttp",
"Microsoft.xmlHttp");
for(var i=0;i<xmlHttpVersions.length&&!xmlHttp;i++)
{
xmlHttp=new ActiveXObject(xmlHttpVersions[i]);
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpRequest Object.");
else
return xmlHttp;
}
</script>
這些就是我從搜集的資料裡匯總出的一個方法,也許不適合你,權作拋磚引玉。
注意這裡的Session(“ServerBaseURL”)是網站的Root URL,後面加了一個隨機數來防止Cache動作。