1. 程式人生 > >ASP.NET單點登錄(代碼)

ASP.NET單點登錄(代碼)

方法 利用 tar 方便 單點 else sta new t key

由於某些原因,在我們的應用中會遇到一個用戶只能在一個地方登錄的情況,也就是我們通常所說的單點登錄。在ASP.NET中實現單點登錄其實很簡單,下面就把主要的方法和全部代碼進行分析。[/p][p=25, null, left]實現思路[/p][p=25, null, left]利用Cache的功能,我們把用戶的登錄信息保存在Cache中,並設置過期時間為Session失效的時間,因此,一旦Session失效,我們的Cache也過期;而Cache對所有的用戶都可以訪問,因此,用它保存用戶信息比數據庫來得方便。[/p]
[p=25, null, left]string sKey = username.Text.ToString().Trim(); // 得到Cache中的給定Key的值

string sUser = Convert.ToString(Cache[sKey]); // 檢查是否存在

if (sUser == null || sUser == String.Empty)

{

TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);//取得Session的過期時間

HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);//將值放入cache己方便單點登錄

//成功登錄

}

else if (Cache[sKey].ToString() == sKey)//如果這個賬號已經登錄

{

ClientScript.RegisterStartupScript(GetType(), "提示", "<script>alert(‘對不起,當前用戶已經登錄‘);</script>");

return;

}

else

{

Session.Abandon();//這段主要是為了避免不必要的錯誤導致不能登錄

}

ASP.NET單點登錄(代碼)