Search code examples
asp.net-coreloggingasp.net-identity

How to log the visits on asp.net-core identity based application


I am using Entity Framework core & ASP.NET core Identity and I want to log who visited the cars/details page. log table only have three columns (visitid, username, visittime).


Solution

  • I am using Entity Framework Core & ASP.NET Core Identity and I want to log who visited the cars/details page. log table only have three columns (visitid, username, visittime).

    I suppose you have created a LogModel which contains the three columns (visitid, username, visittime), and you have generated the related table in the database. If the log table not created, you can refer the following code to create a model, then add migration and update database to generate the table.

    public class LogModel
    {
        public int VisitId { get; set; }
        public string VisitName { get; set; }
        public DateTime VisitTime { get; set; }
    }
    

    Then, in the controller details action method, you can create a new LogModel, when a user visits this action method, it will insert the new LogModel instance into the database. Code like this:

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly MvcMovieContext context;
        public HomeController(ILogger<HomeController> logger, MvcMovieContext movieContext)
        {
            _logger = logger;
            context = movieContext;
        }
    
        public IActionResult Details()
        { 
            //create a new log record.
            var newlog = new LogModel()
            {
                VisitId = 101, //set the value, or set this column as auto increase (Identity).
                VisitName = User.Identity.Name,  //get the current user name through the User.
                VisitTime = DateTime.Now
            };
    
            context.Logs.Add(newlog); //insert into the database 
            context.SaveChanges();  //save change.
    
            return RedirectToAction("Index");
        }
    

    Edit:

    To log current user information into the database using Action Filter method, you could get the current user information and get the request action method name in the Action Filter, and then, insert records into database.

    Code as below:

       public class TestActionFilter:IActionFilter
        {
            private readonly ApplicationDbContext _dbcontext;
    
            public TestActionFilter(ApplicationDbContext context)
            {
                _dbcontext = context;
            }
    
            public void OnActionExecuting(ActionExecutingContext context)
            {
                //get current user name 
                var currentuser = context.HttpContext.User.Identity.Name; 
                //get the request action method, 
                var actionname = context.HttpContext.Request.RouteValues["action"];
                //based on the action method to insert record into database.
                //use _dbcontext to insert data.
                // Do something before the action executes.
                Console.WriteLine("TestActionExecuting:  " + context.HttpContext.Request.Path);
            }
    
            public void OnActionExecuted(ActionExecutedContext context)
            {
                // Do something after the action executes.
                Console.WriteLine("TestActionExecuted:  " + context.HttpContext.Request.Path);
            }
        }
    

    Then, register the action filter in the ConfigureServices method in the Startup.cs file

            services.AddControllersWithViews(options=> {
                options.Filters.Add(typeof(TestActionFilter));
            });
    

    More detail information about ActionFilter, see: Filters in ASP.NET Core