title: Log IP of signed in user with ASP.net core Identity MVC
body: <h2>What I want to achieve:</h2>
  
  <p>Save the IP of a User hitting specific actions/controllers to my database. Also since this process takes a significant amount of time it would be good if it gets executed on a background thread or similar.</p>
  
  <h2>What I tried so far:</h2>
  
  <p>Creating a CustomAuthorizeAttribute that looks something like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>    public class LoggedAuthorizeAttribute : TypeFilterAttribute
      {
          public LoggedAuthorizeAttribute() : base(typeof(LoggedAuthorizeFilter))
          {
          }
      }
  
      public class LoggedAuthorizeFilter : IAuthorizationFilter
      {
          private readonly UserManager&lt;User&gt; _userManager;
  
          public LoggedAuthorizeFilter(UserManager&lt;User&gt; userManager)
          {
              _userManager = userManager;
          }
  
          public async void OnAuthorization(AuthorizationFilterContext context)
          {
              if (!context.HttpContext.User.Identity.IsAuthenticated)
                  return;
  
              var user = await _userManager.GetUserAsync(context.HttpContext.User);
  
              var remoteIpAddress = context.HttpContext.Connection.RemoteIpAddress;
  
              user.UserLogins.Add(new UserLogin
                  {LoggedInOn = DateTimeOffset.UtcNow, LoggedInFrom = remoteIpAddress});
  
              await _userManager.UpdateAsync(user);
          }
      }
  </code></pre>
  
  <p><strong>Problems with this solution:</strong></p>
  
  <ol>
  <li>When the request hits an action marked with this attribute the request will take about 1-2 seconds until it actually processes the action.</li>
  <li>The UserManager is retrieved by Dependency Injection, but I also access the UserManager instance in some of my Actions which causes a <code>InvalidOperationException</code> telling <code>A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.</code>.</li>
  </ol>
  
  <p>Any kind of help is appreciated.</p>
  
  <h2>Update</h2>
  
  <p>As suggested by <code>Kirk Larkin</code> implementing the IAsyncActionFilter instead fixes my second issue I ran into. But still how would I perform this in a Background Thread or similar, if this is even the right choice.</p>