Browse Source

updated AbpAuditingMiddleware

pull/2625/head
Galip Tolga Erdem 7 years ago
parent
commit
1a9fd66be7
  1. 42
      framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs
  2. 6
      framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController_Tests.cs

42
framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs

@ -33,7 +33,7 @@ namespace Volo.Abp.AspNetCore.Auditing
await next(context).ConfigureAwait(false);
return;
}
bool hasError = false;
using (var scope = _auditingManager.BeginScope())
{
try
@ -42,6 +42,7 @@ namespace Volo.Abp.AspNetCore.Auditing
}
catch (Exception)
{
hasError = true;
if (!Options.HideErrors)
{
throw;
@ -49,34 +50,37 @@ namespace Volo.Abp.AspNetCore.Auditing
}
finally
{
await scope.SaveAsync().ConfigureAwait(false);
if (ShouldWriteAuditLog(context, hasError))
{
await scope.SaveAsync().ConfigureAwait(false);
}
}
}
}
private bool ShouldWriteAuditLog(HttpContext httpContext)
private bool ShouldWriteAuditLog(HttpContext httpContext, bool hasError = false)
{
if (Options.AlwaysLogOnException)
if (!Options.IsEnabled)
{
return false;
}
if (Options.AlwaysLogOnException || hasError)
{
return true;
}
if (!Options.IsEnabledForAnonymousUsers && !CurrentUser.IsAuthenticated)
{
return false;
}
if (!Options.IsEnabled)
{
return false;
}
if (!Options.IsEnabledForAnonymousUsers && !CurrentUser.IsAuthenticated)
{
return false;
}
if (!Options.IsEnabledForGetRequests &&
string.Equals(httpContext.Request.Method, HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
{
return false;
}
string.Equals(httpContext.Request.Method, HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
}

6
framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController_Tests.cs

@ -31,6 +31,7 @@ namespace Volo.Abp.AspNetCore.Mvc.Auditing
public async Task Should_Trigger_Middleware_And_AuditLog_Success_For_GetRequests()
{
_options.IsEnabledForGetRequests = true;
_options.AlwaysLogOnException = false;
await GetResponseAsync("api/audit-test/audit-success");
//await _auditingStore.Received().SaveAsync(Arg.Any<AuditLogInfo>()); //Won't work, save happens out of scope
}
@ -38,9 +39,8 @@ namespace Volo.Abp.AspNetCore.Mvc.Auditing
[Fact]
public async Task Should_Trigger_Middleware_And_AuditLog_Exception_Always()
{
_options.IsEnabled = false;
_options.AlwaysLogOnException = false;
_options.HideErrors = false;
_options.IsEnabled = true;
_options.AlwaysLogOnException = true;
await GetResponseAsync("api/audit-test/audit-fail", System.Net.HttpStatusCode.BadRequest);
//await _auditingStore.Received().SaveAsync(Arg.Any<AuditLogInfo>()); //Won't work, save happens out of scope
}

Loading…
Cancel
Save