1

This question may sound trivial, but to me is complicated. I have created a table that stores user's log-in/out date and time. So in my MVC site, I need to be able to insert a new row when the user logs-in and update the row when user clicks on x button or navigates away, etc.

I did a bit of research on "void Session_Start(object sender, EventArgs e)" and thought that might be my solution. However, when I run my site in debug mode in VS, even when I log-out and log-in as another user to the site, the method doesnt get called. Am i missing something, or Session_Start is used for a different purpose?

Any help would be hugely appreciated.

Adnan Niloy
  • 469
  • 11
  • 18
houman_ag
  • 227
  • 3
  • 14
  • what kind of membership you are using ? – Anirudha Gupta May 04 '17 at 03:43
  • Identity Individual User Account – houman_ag May 04 '17 at 03:57
  • see if it's work http://stackoverflow.com/a/28088765/713789 – Anirudha Gupta May 04 '17 at 04:00
  • I'm not an expert in this area, so I'm sorry if this is obvious and I'm not getting it. I just dont see how I can use the offered solution in my problem. The linked page discusses how to redirect user to the log-in page if the Context object is null when logging out. I simply need to detect when the user has logged-in and when s/he is logging-out. – houman_ag May 04 '17 at 04:18
  • Is your Session_Start in the global.asax? – Kevin Raffay May 04 '17 at 04:35
  • did you know how to actionfilterattribute, make one and apply it, in debugging check what is the value url called when it's logout. you need to write conditions to put your code on it, in same code call model and store the logout time and other info. – Anirudha Gupta May 04 '17 at 08:26

1 Answers1

1

Example:

     //Model

        {
    public class LoginHistory
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public DateTime LoginTime { get; set; }
        public DateTime? LogoutTime { get; set; }
        [StringLength(128)]
        public string UsertId { get; set; }
    }
//Controller
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            //............

            switch (result)
            {
                case SignInStatus.Success:
                    LoginTime(model.UserName);
                    return RedirectToLocal(returnUrl);
                //...........
            }
        }

                [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //...............................

            LogOutTime(User.Identity.GetUserId());

            //...............................

            return RedirectToAction("Index", "Home");
        }

         public void LoginTime(string userName)
        {
            using (var db = new Applicationdbcontext())
            {
                var user = db.user.Find(u => u.UserName == userName);
                var model = new LoginHistory
                {
                    UserId = user.Id,
                    LoginTime = DateTime.UtcNow
                    LogoutTime = null,
                };
                db.loginhistory.Add(model);
                db.SaveChanges();
            }

        public void LogOutTime(string userId)
        {
            using (var db = new Applicationdbcontext())
            {
                var model = db.loginhistory.Where(u => u.Uid == userId).OrderByDescending(u => u.Id).First();
                model.LogoutTime = DateTime.UtcNow;
                _login.SaveChanges();
            }
        }

<script type='text/javascript'>
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

$(window).on("beforeunload", function() { 
        if(!inFormOrLink){
            document.getElementById('logoutForm').submit();
        }
}) 

add this script in your layout page. I always follow this example. Hopefully it's help for you.

Ashiquzzaman
  • 5,129
  • 3
  • 27
  • 38
  • Thanks @Ashiquzzaman for the code. The only thing that i dont understand here is when I'm in debug mode and i close the browser tab, the user doesnt log out somehow so the LogOff method doesnt get called. What am I missing? – houman_ag May 05 '17 at 01:51
  • Thanks for the help. My navbar is not only links, there is also some navigation using javascript so the script you included didnt completely work for me. What I ended up doing was to have some code in login/logoff/session_start and session_end methods. This way I catch all possible scenarios. Thanks again for your help. – houman_ag May 07 '17 at 19:45