Introduction

In real-world web applications, tracking user activity is essential for security, auditing, and analytics. One of the most common requirements is to record when a user logs in and logs out.

In this article, we will build a simple and effective system in ASP.NET MVC to track user login and logout time using an audit log table.

Why Do We Need Audit Tracking?

Tracking login and logout activity helps in:

Features Implemented

Database Design

We will use two tables: users and auditlogs.

CREATE TABLE users (
    Id INT IDENTITY PRIMARY KEY,
    Name NVARCHAR(100),
    Contact NVARCHAR(21),
    Email NVARCHAR(150),
    Password NVARCHAR(200)
);

CREATE TABLE auditlogs (
    AuditId INT PRIMARY KEY IDENTITY,
    UserId INT,
    Username NVARCHAR(100),
    LoginDate DATETIME,
    LogoutDate DATETIME NULL
);

Explanation

Step 1: Login Logic

When a user logs in successfully:

loginc

public void InsertLogin(int userId, string username)
{
    string query = @"INSERT INTO auditlogs (UserId, Username, LoginDate)
                     VALUES (@UserId, @Username, GETDATE())";

    using (SqlConnection con = new SqlConnection(_connectionString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@UserId", userId);
        cmd.Parameters.AddWithValue("@Username", username);

        con.Open();
        cmd.ExecuteNonQuery();
    }
} 

Step 2: Logout Logic

When the user logs out:

logoutc
public void UpdateLogout(int userId)
{
    string query = @"UPDATE auditlogs
                     SET LogoutDate = GETDATE()
                     WHERE UserId = @UserId AND LogoutDate IS NULL";

    using (SqlConnection con = new SqlConnection(_connectionString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@UserId", userId);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

Important Note

We use LogoutDate IS NULL to ensure only the active session is updated.

Step 3: Controller Implementation

Login Action

[HttpPost]
public IActionResult Login(string email, string password)
{
    var user = _userService.GetUser(email, password);

    if (user != null)
    {
        HttpContext.Session.SetInt32("UserId", user.Id);
        HttpContext.Session.SetString("Username", user.Name);

        _auditService.InsertLogin(user.Id, user.Name);

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

    ViewBag.Error = "Invalid Credentials";
    return View();
}

Logout Action

public IActionResult Logout()
{
    int? userId = HttpContext.Session.GetInt32("UserId");

    if (userId != null)
    {
        _auditService.UpdateLogout(userId.Value);
    }

    HttpContext.Session.Clear();
    return RedirectToAction("Login");
}

Output

After login and logout operations, the auditlogs table will store data like:

audit
UserIdUsernameLoginDateLogoutDate
1Sandip2026-04-10 10:00 AM2026-04-10 10:30 AM

Best Practices

Common Mistakes

Conclusion

In this article, we implemented a simple audit tracking system in ASP.NET MVC to record user login and logout time.

This approach can be extended further to include additional tracking details such as IP address, device information, and user activity logs.