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:
Monitoring user sessions
Maintaining security logs
Analyzing user behavior
Debugging issues related to authentication
Features Implemented
User login system
Session management
Login time recording
Logout time update
Audit log tracking
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
LoginDatestores the login timestampLogoutDateis initially NULL and updated during logoutEach login creates a new record in
auditlogs
Step 1: Login Logic
When a user logs in successfully:
Validate credentials
Store session values
Insert login time into audit table

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:
Find the latest active session
Update logout time


Join the conversation! Your thoughts help the community grow.