On the current version, the Target object can only be assigned at AuditScope
creation, which you don't control when using Audit.Mvc
extension.
Of course you can do it manually like this:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
SetTargetObject(leaveRequest);
// ... I guess here the leaveRequest object is modified
leaveRequest.SomeProp = "NewValue";
UpdateTargetObject(leaveRequest);
}
private void SetTargetObject(object value)
{
var scope = this.GetCurrentAuditScope();
scope.Event.Target = new AuditTarget
{
SerializedOld = scope.DataProvider.Serialize(value),
Type = value.GetType().Name
};
}
private void UpdateTargetObject(object value)
{
var scope = this.GetCurrentAuditScope();
scope.Event.Target.SerializedNew = scope.DataProvider.Serialize(value);
}
I will provide a way to re-assign the Target Getter in the next version of the library (really soon), so this kind of use case can be simplified.
But if you only need one version of the leaveRequest
object, you can just use a Custom Field:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
this.GetCurrentAuditScope().SetCustomField("LeaveRequest", leaveRequest);
// ...
}
Update
Starting on version 14.2.1, the library exposes a SetTargetGetter(Func<object>)
method on the AuditScope
to update the target getter (a function that returns the target object to audit).
So the first example now can be simplified as:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
this.GetCurrentAuditScope().SetTargetGetter(() => leaveRequest);
// ...
leaveRequest.SomeProp = "NewValue";
}