0

I am maintaining an app that is used by about 30 users. I would like to log to a database every time a user starts the app. Where would I put such a logging method to avoid the method being called every new page that the user visits?

Constructor of controller?

d00d
  • 688
  • 1
  • 8
  • 29
  • 1
    What do you mean: "starts the app"? Login? Is this a web app(assuming so since you said controller)? If not, what type of application is it? – peinearydevelopment Jun 18 '20 at 13:10
  • Yes, it's a MVVM web app.There is no login, we use Windows Authentication. I just saw here that a controller is generated for every request. That means the controller's constructor would be the wrong spot to place a logging method, right? https://stackoverflow.com/questions/1763775/asp-net-mvc-controller-lifecycle – d00d Jun 18 '20 at 13:16
  • I just confirmed that. Every page visit is logged individually if i put the method in the controller's constructor. – d00d Jun 18 '20 at 13:28
  • Using Windows Auth would imply a login. It doesn't mean users have to enter credentials, but you have some mechanism that determines whether or not a user can access a given resource. That is probably tied to a cookie. Somewhere in there would be the place you would want. Controller constructor definitely isn't the place as they are constructed for every request. App startup also has nothing to do with user's first visit. – peinearydevelopment Jun 18 '20 at 13:29
  • Does your app use session ? You could than use HttpContext.Session in a middleware? – AardVark71 Jun 18 '20 at 13:32
  • No we don£t use such things as sessions or cookies so far... – d00d Jun 18 '20 at 14:01

1 Answers1

0

I have now managed to implement this using sessions:

The controller:

public MyController(IHttpContextAccessor httpContextAccessor)
{


    if (string.IsNullOrEmpty(httpContextAccessor.HttpContext.Session.GetString("login")))
    {
        LoginStatistics("Henry Miller");
        httpContextAccessor.HttpContext.Session.SetString("samLogin", "1");
    }
}


private void LoginStatistics(string userLogin)
{
            myContext.LoginStatistics.Add(new LoginStatistics
            {
                Controller = "MyController",
                UserId = userLogin,
                TimeOfLogin = DateTime.Now
            });
            myContext.SaveChanges();
}
d00d
  • 688
  • 1
  • 8
  • 29