首页 > 解决方案 > Audit.Net,-即使抛出异常也需要正确的审计

问题描述

在Controller中执行此方法时:

[Route("deleteIncCloseOut")]
[HttpDelete]
[AuditApi]
public bool deleteIncidentCloseOut(int ID)
{
  try
  {
    using (ESSDataContext ctx = new ESSDataContext())
    {
      ctx.DeleteIncidentCloseOut(ID);
      this.GetCurrentAuditScope().SetCustomField("Dynamic", new { IncidentCloseOutID = ID });
      return true;
    }
  }
  catch (Exception ex)
  {
    log.Error($"{ex.StackTrace}");
    return false;
    throw ex;
  }
}

存储过程存在异常DeleteIncidentCloseOut(ID),因此未设置 AuditEvent 的 CustomField。但是,DataProvider 的 InsertEvent 仍在执行中。

我的问题是在我的 InsertEvent 中我必须填充两个表。一个表包含审计事件的简要描述,另一个包含设置为 AuditEvent 对象的 CustomField 的对象的属性和值。在本例中,我创建了一个以 ID 作为属性的动态对象。所以,我在我的第一个表中获得了 IncidentCloseOut 已被删除的条目(但实际上它没有,因为引发了异常),但我没有在第二个表中获得所谓的删除事件的 ID(因为那里没有设置 CustomField)。所以我得到了虚假的审计信息。最好,存储过程不会抛出异常,但我希望审计是正确的,即使抛出异常也是如此。

我该如何纠正/改善这种情况?

标签: c#audit.net

解决方案


只需在调用引发异常的存储过程之前设置自定义字段:

public bool deleteIncidentCloseOut(int ID)
{
  try
  {
    using (ESSDataContext ctx = new ESSDataContext())
    {
      this.GetCurrentAuditScope().SetCustomField("Dynamic", new { IncidentCloseOutID = ID });
      ctx.DeleteIncidentCloseOut(ID);
      return true;
    }
  }
  catch (Exception ex)
  {
    ...
  }
}

推荐阅读