I am setting up Audit.NET using the below configuration
Configuration.Setup()
.UseEntityFramework(_ => _
.AuditTypeMapper(t => typeof(AuditLog))
.AuditEntityAction<AuditLog>((ev, entry, entity) =>
{
entity.AuditData = entry.ToJson();
entity.TableName = entry.EntityType.Name;
entity.CreatedDate = DateTime.Now;
entity.CreatedBy = Environment.UserName;
entity.TablePK = entry.PrimaryKey.First().Value.ToString();
})
.IgnoreMatchedProperties(true));
However here Environment.UserName is giving windows user name and not the logged in username.
Elsewhere in the application I am able to get the logged in user name like
User.FindFirstValue(ClaimTypes.Name)
How can I acheive this?
There are some ways this can be accomplished, but ultimately it will depend on your specific use case.
If you can't (or don't want to) change your
DbContext, you can have a custom action to resolve the HTTP context accessor from the DbContext.For example, in your
program.cs:Another way, assuming your audited
DbContextinherits fromAuditDbContext, is to Inject theIHttpContextAccessorto yourDbContextconstructor (or use the GetService extension method) to retrieve the user and set a custom audit field with the username.For example:
or just: