Programmatically logout an ASP.NET user

前端 未结 4 1748
小蘑菇
小蘑菇 2020-12-01 08:23

My app allows an admin to suspend/unsuspend user accounts. I do this with the following code:

MembershipUser user = Membership.GetUser(Guid.Parse(userId));
u         


        
4条回答
  •  借酒劲吻你
    2020-12-01 08:28

    There's no way to abandon a session from 'outside' the session. You would have to check the database on each page load, and if the account has been disabled, then signout. You could achieve this using a HttpModule too, which would make things a bit cleaner.

    For example:

    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");
            }
        }
    }
    

    This isn't a complete example, and the method of retrieving the user using a key stored in the session will need to be adapted, but this should get you started. It will involve an extra database check on each page load to check that the user account is still active, but there's no other way of checking this information.

提交回复
热议问题