private async Task <AuditApiAction> CreateOrUpdateAction(ActionExecutingContext actionContext, bool includeHeaders, bool includeRequestBody, bool serializeParams, string eventTypeName) { var httpContext = actionContext.HttpContext; var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor; AuditApiAction action = null; if (httpContext.Items.ContainsKey(AuditApiHelper.AuditApiActionKey)) { action = httpContext.Items[AuditApiHelper.AuditApiActionKey] as AuditApiAction; } if (action == null) { action = new AuditApiAction { UserName = httpContext.User?.Identity.Name, IpAddress = httpContext.Connection?.RemoteIpAddress?.ToString(), HttpMethod = httpContext.Request.Method, FormVariables = AuditApiHelper.GetFormVariables(httpContext), TraceId = httpContext.TraceIdentifier, ActionExecutingContext = actionContext }; } action.RequestUrl = httpContext.Request.GetDisplayUrl(); action.ActionName = actionDescriptor != null ? actionDescriptor.ActionName : actionContext.ActionDescriptor.DisplayName; action.ControllerName = actionDescriptor?.ControllerName; action.ActionParameters = GetActionParameters(actionDescriptor, actionContext.ActionArguments, serializeParams); if (includeHeaders) { action.Headers = AuditApiHelper.ToDictionary(httpContext.Request.Headers); } if (includeRequestBody && action.RequestBody == null) { action.RequestBody = new BodyContent { Type = httpContext.Request.ContentType, Length = httpContext.Request.ContentLength, Value = await AuditApiHelper.GetRequestBody(httpContext) }; } return(action); }
private async Task BeforeInvoke(HttpContext context, bool includeHeaders, bool includeRequestBody, string eventTypeName) { var auditAction = new AuditApiAction { IsMiddleware = true, UserName = context.User?.Identity.Name, IpAddress = context.Connection?.RemoteIpAddress?.ToString(), RequestUrl = context.Request.GetDisplayUrl(), HttpMethod = context.Request.Method, FormVariables = AuditApiHelper.GetFormVariables(context), Headers = includeHeaders ? AuditApiHelper.ToDictionary(context.Request.Headers) : null, ActionName = null, ControllerName = null, ActionParameters = null, RequestBody = new BodyContent { Type = context.Request.ContentType, Length = context.Request.ContentLength, Value = includeRequestBody ? AuditApiHelper.GetRequestBody(context) : null }, TraceId = context.TraceIdentifier }; var eventType = (eventTypeName ?? "{verb} {url}").Replace("{verb}", auditAction.HttpMethod) .Replace("{url}", auditAction.RequestUrl); // Create the audit scope var auditEventAction = new AuditEventWebApi() { Action = auditAction }; var auditScope = await AuditScope.CreateAsync(new AuditScopeOptions() { EventType = eventType, AuditEvent = auditEventAction }); context.Items[AuditApiHelper.AuditApiActionKey] = auditAction; context.Items[AuditApiHelper.AuditApiScopeKey] = auditScope; }