title: Returning null on httpContextAccessor.HttpContext
body: <p>We override SaveChangesAsync() to update automatically for DateCreated, CreatedBy, LastDateModified and LastModifiedBy. With CreatedBy and LastModifiedBt, we need to the User Id of Identity.</p>
  
  <p>In our constructor for ApplicationDbContext, we've added something like this:</p>
  
  <p><code>_userName = httpContextAccessor.HttpContext.User.Identity.Name;
  //_userID = userManager.GetUserId(httpContext.HttpContext.User);</code></p>
  
  <p>.. and always get the null in this httpContextAccessor.HttpContext. Any ideas? We included the source below.</p>
  
  <p><strong>Environment:</strong></p>
  
  <p>.NET Core 2.1</p>
  
  <p>SQL Server</p>
  
  <p><strong>ApplicationDBContext.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Text;
  using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
  using Microsoft.EntityFrameworkCore;
  using AthlosifyWebArchery.Models;
  using System.Linq;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Linq.Expressions;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Identity;
  
  namespace AthlosifyWebArchery.Data
  {
      public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser, ApplicationRole, string&gt;
      {
          private readonly string _userID;
          private readonly string _userName;
  
  
          public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options,
                  IHttpContextAccessor httpContextAccessor
                  )
          : base(options)
          {
              _userName = httpContextAccessor.HttpContext.User.Identity.Name;
  
              //_userID = userManager.GetUserId(httpContext.HttpContext.User);
  
          }
  
          public DbSet&lt;AthlosifyWebArchery.Models.TournamentBatchItem&gt; TournamentBatchItem { get; set; }
          public DbSet&lt;AthlosifyWebArchery.Models.TournamentBatch&gt; TournamentBatch { get; set; }
  
          public virtual DbSet&lt;AthlosifyWebArchery.Models.Host&gt; Host { get; set; }
  
          public DbSet&lt;AthlosifyWebArchery.Models.HostApplicationUser&gt; HostApplicationUser { get; set; }
  
          protected override void OnModelCreating(ModelBuilder builder)
          {
              base.OnModelCreating(builder);
  
              foreach (var entityType in builder.Model.GetEntityTypes())
              {
                  // 1. Add the IsDeleted property
                  entityType.GetOrAddProperty("IsDeleted", typeof(bool));
  
                  // 2. Create the query filter
  
                  var parameter = Expression.Parameter(entityType.ClrType);
  
                  // EF.Property&lt;bool&gt;(post, "IsDeleted")
                  var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
                  var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted"));
  
                  // EF.Property&lt;bool&gt;(post, "IsDeleted") == false
                  BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false));
  
                  // post =&gt; EF.Property&lt;bool&gt;(post, "IsDeleted") == false
                  var lambda = Expression.Lambda(compareExpression, parameter);
  
                  builder.Entity(entityType.ClrType).HasQueryFilter(lambda);
              }
  
  
              // Many to Many relationship
  
              builder.Entity&lt;HostApplicationUser&gt;()
                  .HasKey(bc =&gt; new { bc.HostID, bc.Id });
  
  
              builder.Entity&lt;HostApplicationUser&gt;()
                  .HasOne(bc =&gt; bc.Host)
                  .WithMany(b =&gt; b.HostApplicationUsers)
                  .HasForeignKey(bc =&gt; bc.HostID);
  
              builder.Entity&lt;HostApplicationUser&gt;()
                  .HasOne(bc =&gt; bc.ApplicationUser)
                  .WithMany(c =&gt; c.HostApplicationUsers)
                  .HasForeignKey(bc =&gt; bc.Id);
  
          }
  
          public override int SaveChanges(bool acceptAllChangesOnSuccess)
          {
              OnBeforeSaving();
              return base.SaveChanges(acceptAllChangesOnSuccess);
          }
  
          public override Task&lt;int&gt; SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
          {
              OnBeforeSaving();
              return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
          }
  
          private void OnBeforeSaving()
          {
              // Added
              var added = ChangeTracker.Entries().Where(v =&gt; v.State == EntityState.Added &amp;&amp; typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();
  
              added.ForEach(entry =&gt;
              {
                  ((IBaseEntity)entry.Entity).DateCreated = DateTime.UtcNow;
                  ((IBaseEntity)entry.Entity).CreatedBy = _userID;
                  ((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
                  ((IBaseEntity)entry.Entity).LastModifiedBy = _userID;
              });
  
              // Modified
              var modified = ChangeTracker.Entries().Where(v =&gt; v.State == EntityState.Modified &amp;&amp; 
              typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();
  
              modified.ForEach(entry =&gt;
              {
                  ((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
                  ((IBaseEntity)entry.Entity).LastModifiedBy = _userID;
              });
  
              // Deleted
              //var deleted = ChangeTracker.Entries().Where(v =&gt; v.State == EntityState.Deleted &amp;&amp;
              //typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();
  
              var deleted = ChangeTracker.Entries().Where(v =&gt; v.State == EntityState.Deleted).ToList();
  
              deleted.ForEach(entry =&gt;
              {
                  ((IBaseEntity)entry.Entity).DateDeleted = DateTime.UtcNow;
                  ((IBaseEntity)entry.Entity).DeletedBy = _userID;
              });
  
              foreach (var entry in ChangeTracker.Entries()
                                      .Where(e =&gt; e.State == EntityState.Deleted &amp;&amp;
                                      e.Metadata.GetProperties().Any(x =&gt; x.Name == "IsDeleted")))
              {
                  switch (entry.State)
                  {
                      case EntityState.Added:
                          entry.CurrentValues["IsDeleted"] = false;
                          break;
  
                      case EntityState.Deleted:
                          entry.State = EntityState.Modified;
                          entry.CurrentValues["IsDeleted"] = true;
                          break;
                  }
              }
          }
      }
  
  
  
  }
  </code></pre>
  
  <p><strong>Startup.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Identity;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.HttpsPolicy;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.EntityFrameworkCore;
  using AthlosifyWebArchery.Data;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using AthlosifyWebArchery.Models;
  using DinkToPdf.Contracts;
  using DinkToPdf;
  
  namespace AthlosifyWebArchery
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              //services.AddHttpContextAccessor();
  
              services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
              services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
  
              services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
              {
                  // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                  options.CheckConsentNeeded = context =&gt; true;
                  options.MinimumSameSitePolicy = SameSiteMode.None;
              });
  
              services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
                  options.UseSqlServer(
                      Configuration.GetConnectionString("DefaultConnection")));
  
              // Extended Application User from IdentityUser 
              // and ApplicationRole from IdentityRole
  
              services.AddIdentity&lt;ApplicationUser, ApplicationRole&gt;(
                  options =&gt; options.Stores.MaxLengthForKeys = 128)
                  .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
                  .AddDefaultUI()
                  .AddDefaultTokenProviders();
  
              services.AddMvc()
                  .AddRazorPagesOptions(options =&gt;
                  {
                      options.Conventions.AuthorizeFolder("/Tournaments");
                      options.Conventions.AuthorizeFolder("/TournamentAtheletes");
                      options.Conventions.AuthorizeFolder("/TournamentBatches");
                      options.Conventions.AuthorizeFolder("/TournamentContingents");
                      options.Conventions.AuthorizeFolder("/Admin");
                      //options.Conventions.AuthorizeFolder("/Private");
                      //options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
                      //options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
                  })
                  .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                                  ApplicationDbContext context,
                                  RoleManager&lt;ApplicationRole&gt; roleManager,
                                  UserManager&lt;ApplicationUser&gt; userManager)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
                  app.UseDatabaseErrorPage();
              }
              else
              {
                  app.UseExceptionHandler("/Error");
                  app.UseHsts();
              }
  
              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseCookiePolicy();
  
              app.UseAuthentication();
  
              app.UseMvc();
  
              //UserManagerInitialData.Initialize(context, userManager, roleManager).Wait();
  
          }
  
  
      }
  }
  </code></pre>