2

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.

6
  • what kind of membership you are using ? Commented May 4, 2017 at 3:43
  • Identity Individual User Account Commented May 4, 2017 at 3:57
  • see if it's work stackoverflow.com/a/28088765/713789 Commented May 4, 2017 at 4: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. Commented May 4, 2017 at 4:18
  • Is your Session_Start in the global.asax? Commented May 4, 2017 at 4:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.