简体   繁体   中英

Insert User Logout information After Session Timeout?

I want to make user logout after session timeout and in logout i am inserting value of that particular user make changes in his flag, like if his flag is 1 he is logged in and if his flag is 0 he is log out so i want to change the flag value from 1 to 0 when he logout.

My logout Action:

public ActionResult Logout(short? UserId12)
    {
        FormsAuthentication.SignOut();
        //Session["UserName"] = null;
        //Session["BranchCode"] = null;
        //Session["GroupID"] = null;

        USER_LOGIN obj = new USER_LOGIN();

        obj = db.USER_LOGIN.Find(UserId12);

        obj.LOGOUTFLAG = 0;
        obj.LOGOUT_DATETIME = System.DateTime.Now;
        db.SaveChanges();

        Session.RemoveAll();
        return RedirectToAction("Login", "Account");

    }

I Was trying to solve this by jquery sending userid to action but problem is userid is in session it expires on time out

<script>
    var url= '@Url.Action("Logout", "Account", new { UserId12 = Session["UserId1"] })';
    var sessTm = @Session.Timeout
    sessTm = sessTm * 60;
    sessTm = sessTm - 10;
    function mTmout() {
        sessTm -= 1;
        if (sessTm == 0) {
            window.location = url;
        } else {
            setTimeout(mTmout, 1000);
        }
    };

    $(document).ready(function () {
        $(".tmout").html(sessTm);
        setTimeout(mTmout, 1000);
    });

Try the opposite, that is that the login should populate your session and when the session expires the user would automatically appear logged out.

Do this by having a filter over your app or controller that checks for the logged in session variable and redirects if it doesn't exist.

For example use FilterConfig.cs in the "App_Start" file for app wide coverage:

public class FilterConfig
{
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   {
      filters.add(new LoginFilter());
   }
}

LoginFilter:

public class LoginFilter : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      if(HttpContext.Current.Session["IsLoggedIn"]==false) //or null
      {
         //redirect to login page
      }
   }
}

You will need to implement this for your login controller so you don't get infinite redirect loops: Skip global filter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM