0

I am working on the .Net Core 5.0 Web Application and following the repository pattern with the Unit Of Work Pattern for database operations.

I am accessing and working with the Repository Pattern's interfaces (Code) via the .Net Core Web API Project which communicates back with another Asp.Net Core 5.0 Web Project (Client Side). I have implemented the Asp.Net Core Identity on both the Asp.Net Core 5.0 Web and Web API Projects. I can authenticate and authorize users on the client-side and have created JWT Token on the Web API project for user authentication.

What I want to do is to keep history information on each of my database entities and have added fields for history purposes like CreatedBy, UpdatedBy, CreatedDate, UpdatedDate, and IsActive. For now, there is no record being adding for these fields.

I have researched online and have got an idea of overriding the SaveChanges() method of the IdentityDBContext class and have tried with a few samples but I am unable to get currently logged in userId (User who is logged in on client project) within the repository pattern so that I can use it for CreatedBy and UpdatedBy fields.

I have tried using claims-principle and writing custom service but none of these are helping me to resolve my issue.

I have my IdentityDBContext class within the repository project (this class library project is added as a reference in both my API and Client projects).

Here is my SaveChanges() method in IdentityDBContext class:

public override int SaveChanges()
        {
            var selectedEntityList = ChangeTracker.Entries()
                                    .Where(x => x.Entity is BaseEntity &&
                                    (x.State == EntityState.Added || x.State == EntityState.Modified));

            var userId = _user;

            foreach (var entity in selectedEntityList)
            {

                ((BaseEntity)entity.Entity).CreatedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).UpdatedDate = DateTime.Now;
                ((BaseEntity)entity.Entity).CreatedBy = "";
                ((BaseEntity)entity.Entity).UpdatedBy = "";
            }

            return base.SaveChanges();
        }

Any expert suggestion will be highly appreciated.

Noor
  • 185
  • 2
  • 18

1 Answers1

1

You can get the current user id like below:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public override int SaveChanges()
    {
        var httpContextAccessor = this.GetService<IHttpContextAccessor>();
        var userId = httpContextAccessor.HttpContext?.User
                               .FindFirst(ClaimTypes.NameIdentifier).Value;

        //do your stuff...
    }
}
Rena
  • 30,832
  • 6
  • 37
  • 72