1

I want to save a record and apply the CreatedBy/ModifiedBy GUID (Id) as well as the CreatedOn / ModifiedOn fields from my base dbContext class.

I found this article that looks like what I want to accomplish, but in MVC Core 1.0 you do not have access to System.Web to get to HttpContext.

Another good article that shows what I want to do is this

The code sample I am refering to is this:

public override int SaveChanges()
{
    var changeSet = ChangeTracker.Entries<IAuditable>();
    if (changeSet != null)
    {
        foreach (var entry in changeSet.Where(c => c.State != EntityState.Unchanged))
        {
            entry.Entity.ModifiedDate = DateProvider.GetCurrentDate();
            entry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name;
        }
    }
    return base.SaveChanges();
}

Is there a way to get the HttpContext otherwise in Core Framework?

Community
  • 1
  • 1
MerlinNZ
  • 149
  • 1
  • 11

1 Answers1

1

HttpContext.Current does not exist anymore. You can access it via the IHttpContextAccessor in the following way:

In Startup.cs, add: services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Then:

private readonly IHttpContextAccessor httpContextAccessor_;

public HomeController(IHttpContextAccessor httpContextAccessor)
{
    httpContextAccessor_ = httpContextAccessor;
    var username = httpContextAccessor_.HttpContext.User.Identity.Name;
}

Also note that IHttpContextAccessor will be only available in classes, which are resolved/created by the DI container.

regnauld
  • 4,046
  • 3
  • 23
  • 22