[英]Limit only one session per user in ASP.NET
無論如何檢測用戶何時登錄是否已經有另一個具有相同用戶名的會話,並阻止他再次登錄或向他發送消息?
您始終可以在global.asax中實現事件。
實現Application_Start()以設置System.Collections.Dictionary(或根據您的喜好)並將其存儲在Application []集合中,當用戶登錄時,添加用戶名。 從Session_End()中的集合中刪除。 在使用集合時,請記住使用'lock'關鍵字:)
玩得開心!
例:
[page.aspx]
public partial class page : System.Web.UI.Page {
protected bool Login(string userName) {
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null) {
lock (d) {
if (d.Contains(userName)) {
// User is already logged in!!!
return false;
}
d.Add(userName);
}
}
Session["UserLoggedIn"] = userName;
return true;
}
protected void Logout() {
Session.Abandon();
}
}
[global.asax]
<%@ Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e) {
Application["UsersLoggedIn"] = new System.Collections.Generic.List<string>();
}
void Session_End(object sender, EventArgs e) {
// NOTE: you might want to call this from the .Logout() method - aswell -, to speed things up
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty ? (string)Session["UserLoggedIn"];
if (userLoggedIn.Length > 0) {
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null) {
lock (d) {
d.Remove(userLoggedIn);
}
}
}
}
</script>
我已經實現了這一點,當用戶登錄時,它會在他們登錄的數據庫中設置一個標志。這是一個表示他們登錄多少次的int。我們允許兩個。 然后在驗證用戶時檢查一下。
您可以通過使用Application對象跟蹤用戶登錄的global.asax。
在Session_Start方法或登錄方法中,您可以檢查用戶是否存儲在Application對象中。
在Session_End方法或注銷方法中,您需要從Application對象中刪除用戶。
如果您無法識別用戶注銷事件(他們可能會單擊注銷,關閉選項卡,關閉整個瀏覽器,或者可能只是關閉計算機......),請不要將其存儲在數據庫中。 使用會話來執行相同的檢查。
您可以將用戶的SessionID存儲在數據庫中。 在每次登錄時,將唯一用戶名和SessionID的組合存儲到數據庫中。 在母版頁中,您將查詢包含在數據庫中,以檢查當前使用的用戶名的最后一次登錄是否來自同一會話。 如果沒有,請放棄會話並重定向到登錄頁面。
我發布的行為應該注銷第二個用戶。 您可以將Session.Abandon更改為您想要的行為
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.