Audit.NET EntityFramework

1.2k Views Asked by At

I am trying to replace our own Audit system with Audit.NET. I have checked the documentation for Audit.EntityFramework, https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework, and it is not clear to me where the configuration setup should be added. Also, lets say I am building a ASP.NET CORE RestFUL API and need to keep track of users making changes by extracting user information from a JWT, how would I set that up with Audit.EntityFramework?

In the documentation there is the follow code snippet to configure audits for orders and tracking users :

Audit.Core.Configuration.Setup()
.UseEntityFramework(ef => ef
    .AuditTypeExplicitMapper(m => m
        .Map<Order, Audit_Order>()
        .Map<OrderItem, Audit_OrderItem>()
        .AuditEntityAction<IAudit>((evt, entry, auditEntity) =>
        {
            auditEntity.AuditDate = DateTime.UtcNow;
            auditEntity.UserName = evt.Environment.UserName;
            auditEntity.AuditAction = entry.Action; // Insert, Update, Delete
        })
    )
);

However, if I would add that in the Startup.cs it would not help track what each user is doing on each call made by different users on the different endpoints. Do you have any example of how I can do this using Audit.EntityFramework?

Thanks

1

There are 1 best solutions below

1
On

Have you seen the main Audit.NET documentation?

Yes, the setup must be executed before any audit takes place, so on your start-up code should be fine.

If you need to add more information to the audit events you could use custom actions that also should be setup on your start-up code. That doesn't mean you have to set the value at the start-up, but you have to provide a way to get the value on the start-up. For example if you need something from the current HttpContext, you could get it from an HttpContextAccessor. For example:

public void Configure(IApplicationBuilder app, IHttpContextAccessor contextAccessor)
{
    // ...
    Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
    {
        var httpContext = contextAccessor.HttpContext;
        // Add a new field
        scope.Event.CustomFields["CorrelationId"] = httpContext.TraceIdentifier;
        // reuse an existing field
        scope.Event.Environment.UserName = GetUserFromContext(httpContext);
    });
}

Also, Audit.NET provides two libraries Audit.WebApi and Audit.MVC to audit Web API and/or MVC calls.

Also there is a dotnet new template exposed you could use to quickly create a minimal WebAPI/MVC project with audit enabled and using entity framework. For example:

dotnet new -i Audit.WebApi.Template
dotnet new webapiaudit -E