C#

.NET Audit Logging Guide

Integrate AuditKit into your .NET application with the official C# SDK. Middleware, Entity Framework Core interceptors, and ASP.NET Core integration.

Overview

The AuditKit .NET SDK provides first-class integration with ASP.NET Core and Entity Framework Core. Use middleware for automatic request logging, EF Core interceptors for database change tracking, and the fluent API for explicit event capture. The SDK supports dependency injection, IHostedService for background delivery, and configuration through appsettings.json or environment variables.

Getting started

1

Install the NuGet package

Add AuditKit to your .NET project.

C#
dotnet add package AuditKit.AspNetCore
2

Configure services

Register AuditKit in your DI container.

C#
// Program.cs
builder.Services.AddAuditKit(options =>
{
    options.ApiKey = builder.Configuration["AuditKit:ApiKey"];
    options.TenantResolver = context =>
        context.User.FindFirst("org_id")?.Value;
});
3

Add middleware

Register the AuditKit middleware in the pipeline.

C#
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseAuditKit();  // Add after auth middleware
app.MapControllers();
4

Log events

Inject IAuditKitClient and log events in controllers or services.

C#
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IAuditKitClient _auditkit;

    public UsersController(IAuditKitClient auditkit)
    {
        _auditkit = auditkit;
    }

    [HttpPost("{id}/role")]
    public async Task<IActionResult> ChangeRole(string id, RoleUpdate model)
    {
        var user = await _userService.ChangeRole(id, model.Role);

        await _auditkit.LogAsync(new AuditEvent
        {
            Action = "user.role_changed",
            Actor = new Actor { Id = User.GetUserId(), Email = User.GetEmail() },
            Target = new Target { Type = "user", Id = id },
            Metadata = new { PreviousRole = user.PreviousRole, NewRole = model.Role },
        });

        return Ok(user);
    }
}

Complete example

Here is a complete example showing AuditKit integrated into a .NET application with authentication logging, data access tracking, and explicit event capture.

C#
// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuditKit(options =>
{
    options.ApiKey = builder.Configuration["AuditKit:ApiKey"];
    options.TenantResolver = context =>
        context.User.FindFirst("org_id")?.Value;
    options.EnableEfCoreInterceptor = true;
});

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseAuditKit();
app.MapControllers();
app.Run();

// Controllers/InvoiceController.cs
[ApiController]
[Route("api/[controller]")]
public class InvoicesController : ControllerBase
{
    private readonly IAuditKitClient _auditkit;
    private readonly IInvoiceService _invoiceService;

    public InvoicesController(IAuditKitClient auditkit, IInvoiceService service)
    {
        _auditkit = auditkit;
        _invoiceService = service;
    }

    [HttpPost("{id}/refund")]
    public async Task<IActionResult> Refund(string id)
    {
        var invoice = await _invoiceService.GetByIdAsync(id);
        var previousStatus = invoice.Status;
        await _invoiceService.RefundAsync(id);

        await _auditkit.LogAsync(new AuditEvent
        {
            Action = "invoice.refunded",
            Actor = new Actor
            {
                Id = User.GetUserId(),
                Email = User.GetEmail(),
            },
            Target = new Target { Type = "invoice", Id = id },
            Metadata = new
            {
                InvoiceNumber = invoice.Number,
                Amount = invoice.Amount,
                PreviousStatus = previousStatus,
            },
        });

        return Ok(invoice);
    }
}

Common patterns

ASP.NET Core middleware for automatic request logging

EF Core interceptors for database change tracking

ASP.NET Core Identity event handlers for auth logging

IHostedService for reliable background delivery

Minimal API integration with endpoint filters

MediatR pipeline behavior for CQRS command logging

Frequently asked questions

How do I add audit logging to an ASP.NET Core application?

Install AuditKit.AspNetCore from NuGet, call AddAuditKit() in your service configuration, and add UseAuditKit() to your middleware pipeline. Inject IAuditKitClient into controllers or services for explicit event logging.

Does AuditKit support Entity Framework Core?

Yes. The AuditKit .NET SDK includes an EF Core interceptor that automatically captures database mutations (insert, update, delete) as audit events with before/after state tracking. Enable it with EnableEfCoreInterceptor = true in your configuration.

More integration guides

Related resources

Add audit logging to your .NET app

Get started with tamper-proof audit trails in minutes. Open source, from $99/mo.