Hello,
we have a weird problem - after deploying our project to IIS to get the userName in our "Audit" code doesn't work (ArgumentNullException)...
here is the code:
public class Auditing
{
private static void SetProperty(Type type, EntityEntry entityEntry, string name, object value)
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
entityEntry.Property(name).CurrentValue = value;
}
}
public static void Audit(EntityEntry entityEntry, string userName)
{
var type = entityEntry.Entity.GetType();
if (entityEntry.State == EntityState.Added)
{
SetProperty(type, entityEntry, "Benutzer", userName);
SetProperty(type, entityEntry, "angelegt", DateTime.UtcNow);
}
else if (entityEntry.State == EntityState.Modified)
{
SetProperty(type, entityEntry, "Benutzer", userName);
SetProperty(type, entityEntry, "geändert", DateTime.UtcNow);
SetProperty(type, entityEntry, "gendert", DateTime.UtcNow);
}
}
}
public partial class PdbContext : Microsoft.EntityFrameworkCore.DbContext
{
partial void OnModelBuilding(ModelBuilder builder)
{
builder.Entity<PdbDetektive.Models.Pdb.Pfuscherakt>()
.Property(p => p.Aktenzahl)
.ValueGeneratedOnAddOrUpdate();
}
private readonly IHttpContextAccessor httpAccessor;
public PdbContext(IHttpContextAccessor httpAccessor, DbContextOptions<PdbContext> options):base(options)
{
this.httpAccessor = httpAccessor;
}
public PdbContext(IHttpContextAccessor httpAccessor)
{
this.httpAccessor = httpAccessor;
}
public override int SaveChanges()
{
var userName = httpAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
var auditables = ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (var auditable in auditables)
{
Auditing.Audit(auditable, userName);
}
return base.SaveChanges();
}
}
do you have any idea why the following line works local but not on IIS?
var userName = httpAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
robert