以编程方式注销ASP.NET用户

我的应用程序允许管理员暂停/取消暂停用户帐户。 我使用以下代码执行此操作:

MembershipUser user = Membership.GetUser(Guid.Parse(userId)); user.IsApproved = false; Membership.UpdateUser(user); 

以上工作可以暂停用户,但不会撤销他们的会话。 因此,只要其会话cookie保持不变,被挂起的用户就可以继续访问该应用程序。 任何修复/

没有办法从会议的“外部”放弃会话。 您必须在每个页面加载时检查数据库,如果该帐户已被禁用,则注销。 你也可以使用HttpModule实现这一点,这会让事情变得更清晰。

例如:

 public class UserCheckModule : IHttpModule { public void Init(HttpApplication context) { context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute); } public void Dispose() {} private void OnPreRequestHandlerExecute(object sender, EventArgs e) { // Get the user (though the method below is probably incorrect) // The basic idea is to get the user record using a user key // stored in the session (such as the user id). MembershipUser user = Membership.GetUser(Guid.Parse(HttpContext.Current.Session["guid"])); // Ensure user is valid if (!user.IsApproved) { HttpContext.Current.Session.Abandon(); FormsAuthentication.SignOut(); HttpContext.Current.Response.Redirect("~/Login.aspx?AccountDisabled"); } } } 

这不是一个完整的示例,并且需要调整使用存储在会话中的密钥来检索用户的方法,但这应该可以帮助您入门。 它将涉及对每个页面加载进行额外的数据库检查,以检查用户帐户是否仍处于活动状态,但没有其他方法可以检查此信息。

如果使用表单身份validation

 FormsAuthentication.SignOut(); 

当您注销用户时,覆盖FormsAuthenticationTicket也是一个好主意。

 HttpContext context = HttpContext.Current; //overwrite the authentication cookie FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, context.User.Identity.Name, DateTime.Now, DateTime.Now.AddDays(-1), false, Guid.NewGuid().ToString()); string encrypted_ticket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted_ticket); cookie.Expires = ticket.Expiration; context.Response.Cookies.Add(cookie); //clear all the sessions context.Session.Abandon(); //sign out and go to the login page FormsAuthentication.SignOut(); FormsAuthentication.RedirectToLoginPage(); 

在某个常见页面上,检查帐户是否有效,如果已被撤销,请调用Session.Abandon()

编辑 (注意到这仍然是开放的。)

我知道这很有效,因为我做到了。

在母版页上,检查帐户状态。 这意味着在每次导航时您都有机会将其注销。

(最后)编辑

不要将其视为“我正在终止他们的会话”,将其视为“他们的会话终止自己”。