Search code examples
c#entity-framework-coreaudit.net

Cannot get Auditing of EntityFramework Core to work


First, I installed the Audit Template and created a new project using the Audit.Net template. Using that project as a guide I tried to implement auditing on my actual project where I have an Asp.Net Core API (Project Name: EcommerceAPI). It also uses Entity Framework Core (in Library Project: Persistence). I have installed these NuGet packages only to EcommerceAPI:

  • Audit.EntityFramework.Core v18.1.3
  • Audit.WebApi.Core v18.1.3

Here is my AuditConfiguration.cs file:

public static class AuditConfiguration
{
    private const string CorrelationIdField = "CorrelationId";

    /// <summary>
    /// Add the global audit filter to the MVC pipeline
    /// </summary>
    public static MvcOptions AddAudit(this MvcOptions mvcOptions)
    {
        // Configure the global Action Filter
        mvcOptions.AddAuditFilter(a => a
                .LogAllActions()
                .WithEventType("MVC:{verb}:{controller}:{action}")
                .IncludeModelState()
                .IncludeRequestBody()
                .IncludeResponseBody());
        return mvcOptions;
    }

    /// <summary>
    /// Global Audit configuration
    /// </summary>
    public static IServiceCollection ConfigureAudit(this IServiceCollection serviceCollection)
    {
        // TODO: Configure the audit data provider and options. For more info see https://github.com/thepirat000/Audit.NET#data-providers.
        Audit.Core.Configuration.Setup()
            .UseDynamicProvider(_ => _.OnInsert(auditEvent =>
            {
                if (auditEvent.Environment.Exception != null)
                {
                    Log.Error("Audit Exception in {CallingMethodName}: {Exception}", auditEvent.Environment.CallingMethodName, auditEvent.Environment.Exception);
                }
                else
                {
                    Log.Information("Audit Event: {EventType} {Duration}", auditEvent.EventType, auditEvent.Duration);
                }
            }))
            .WithCreationPolicy(EventCreationPolicy.InsertOnEnd);

        // Entity framework audit output configuration
        Audit.EntityFramework.Configuration.Setup()
            .ForContext<EntityContext>(_ => _
                .AuditEventType("EF:{context}"))
            .UseOptOut();

        return serviceCollection;
    }

    public static void UseAuditMiddleware(this IApplicationBuilder app)
    {
        // Configure the Middleware
        app.UseAuditMiddleware(_ => _
            .FilterByRequest(r => !r.Path.Value.EndsWith("favicon.ico"))
            .IncludeHeaders()
            .IncludeRequestBody()
            .IncludeResponseBody()
            .WithEventType("HTTP:{verb}:{url}"));
    }

    /// <summary>
    /// Add a RequestId so the audit events can be grouped per request
    /// </summary>
    public static void UseAuditCorrelationId(this IApplicationBuilder app, IHttpContextAccessor ctxAccesor)
    {
        
        Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
        {
            var httpContext = ctxAccesor.HttpContext;
            scope.Event.CustomFields[CorrelationIdField] = httpContext.TraceIdentifier;
        });
    }
}

The Asp.Net Core audits just fine. However, I get nothing from Entityframework Core audits. Do I need to change anything in my Persistence Library Project to get auditing to work? Should I install the Audit.EntityFramework.Core Nuget package to the library? I can post my Startup.cs file if anybody thinks they need it. Any help will be appreciated.


Solution

  • O.K. I had not gone all the way through the docs. This my failure to RTFM.

    I needed to install Audit.EntityFramework.Core on Persistence and change my DbContext to AuditDbContext. It is simple as that.