Audit Filter
public class AuditFilter : IAsyncActionFilter
{
/// <summary>
/// The Logger
/// </summary>
private readonly ILogger<AuditFilter> logger;
/// <summary>
/// Constructs an Audit Filter
/// </summary>
/// <param name="logger"></param>
public AuditFilter(ILogger<AuditFilter> logger)
{
this.logger = logger;
}
/// <summary>
/// This method is called just before an action is invoked
/// </summary>
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
LogRequest(context);
await next();
}
/// <summary>
/// Logs the request information about the request
/// </summary>
/// <param name="context">The Action Executing Context</param>
private void LogRequest(ActionExecutingContext context)
{
Dictionary<string, object> routeData = null;
if (context.HttpContext.Request.ContentType == null
|| !context.HttpContext.Request.ContentType.Contains("multipart/form-data"))
routeData = context.ActionArguments?.ToDictionary(kv => kv.Key, kv => kv.Value);
var request = new
{
RequestId = context.HttpContext.TraceIdentifier, // Request identifier ({ConnectionId:RequestNumber}) generated by Kestrel
RouteData = routeData, // Route parameters (including anything taken from request body)
UserId = context.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value, // User Id
Name = context.HttpContext.User?.FindFirst(ClaimTypes.Name)?.Value, // User Name
Date = DateTime.UtcNow, // Date and time in UTC
Operation = $"{context.HttpContext.Request.Path}-{context.HttpContext.Request.Method}", // Endpoint - HTTP verb
};
logger.LogInformation(JsonConvert.SerializeObject(request));
}
}
No comments:
Post a Comment