1

Using Audit.Net is it possible to create an audit scope for httpClient requests, in a similar way to the MVC.Core or WebAPI.Core Middleware?

I've tried something like this but not having much success, generally it'll timeout the app.

AuditScope scope = null;
try {
 using(HttpClient client = new HttpClient) {

  scope = await AuditScope.CreateAsync("",() => client)
  // code to initialise the Httpclient
 }
}
finally {
 await scope.DisposeAsync();
}
Bert McKay
  • 26
  • 1
  • 5

1 Answers1

1

I think the only option to hook into the HttpClient is to use a custom HttpClientHandler so you can intercept the rest calls.

Just as an example:

public class AuditClientHandler : HttpClientHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var options = new AuditScopeOptions()
        {
            EventType = $"{request.Method.Method} {request.RequestUri.AbsoluteUri}",
            CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd,
            ExtraFields = new
            {
                request = GetRequestAudit(request)
            }
        };
        using (var scope = AuditScope.Create(options))
        {
            var response = await base.SendAsync(request, cancellationToken);
            scope.SetCustomField("response", GetResponseAudit(response));
            return response;
        } 
    }
}

I've used the InsertOnStartReplaceOnEnd creation policy, so the request is saved before it's sent to the server, and the response is added to the event and saved afterwards.

The implementation of GetRequestAudit / GetResponseAudit is up to you, just return an object (that can be serialized) with the information you want to log.

So each time you need to audit an HttpClient instance, you need to pass the handler to its constructor:

var cli = new HttpClient(new AuditClientHandler());
var response = await cli.GetAsync("http://google.com");

Anyway I will evaluate providing a new library (Audit.HttpClient?) with a configurable Handler so the implementation could be cleaner.

Update

You can now use the Audit.HttpClient extension for a cleaner implementation. Take a look at the documentation here

thepirat000
  • 12,362
  • 4
  • 46
  • 72