Audit.HttpClient

April 9, 2025 ยท View on GitHub

HttpClient audit extension for Audit.NET library.

Generate Audit Logs by intercepting HttpClient REST calls. Audit.HttpClient provides the infrastructure to create audit logs for an instance of HttpClient class.

It relies on a message handler to incercept the calls to HttpClient methods.

Install

NuGet Package

To install the package run the following command on the Package Manager Console:

PM> Install-Package Audit.HttpClient

NuGet Status NuGet Count

Usage

To enable the audit log for HttpClient, you have to set an AuditHttpClientHandler as a message handler for the HttpClient instance being audited.

This can be done in different ways:

  • Call the factory provided by Audit.Http.ClientFactory.Create() method to get a new audit-enabled instance of HttpClient:
var httpClient = Audit.Http.ClientFactory.Create(_ => _
    .IncludeRequestBody()
    .IncludeResponseHeaders()
    .FilterByRequest(req => req.Method.Method == "GET"));

The ClientFactory.Create method is just a shortcut to create a new HttpClient with a custom AuditHttpClientHandler as its message handler.

  • If you use ASP .NET dependency injection / HttpClientFactory, you can add the message handler with the extension method AddAuditHandler() on your startup:
using Audit.Http;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient("GitHub", c =>
        {
            c.BaseAddress = new Uri("https://api.github.com/");
        })
        .AddAuditHandler(audit => audit
            .IncludeRequestBody()
            .IncludeResponseHeaders());
    }
}

Note: AddAuditHandler(config) is a shortcut for AddHttpMessageHandler(() => new AuditHttpClientHandler(config))

  • You can also create an audited HttpClient passing the handler to its constructor:
var httpClient = new HttpClient(new AuditHttpClientHandler(_ => _
    .IncludeRequestBody()
    .IncludeResponseHeaders());

Each method call on the audited HttpClient instances will generate an Audit Event.

Configuration

Output

The audit events are stored using a Data Provider. You can use one of the available data providers or implement your own. Please refer to the data providers section on Audit.NET documentation.

Settings

The AuditHttpClientHandler class allows to configure the following settings:

  • RequestFilter / FilterByRequest: Set a filter function to determine which events to log depending on the request message. By default all events are logged.
  • ResponseFilter / FilterByResponse: Set a filter function to determine which events to log depending on the response message. By default all events are logged.
  • EventType: A string that identifies the event type. Default is "{verb} {url}". It can contain the following placeholders:
    • {verb}: Replaced by the Http Verb (GET, POST, ...)
    • {url}: Replaced by the request URL
  • IncludeRequestHeaders: Specifies whether the HTTP Request headers should be included on the audit output. Default is false.
  • IncludeResponseHeaders: Specifies whether the HTTP Response headers should be included on the audit output. Default is false.
  • IncludeContentHeaders: Specifies whether the HTTP Content headers should be included on the audit output. Default is false.
  • IncludeRequestBody: Specifies whether the HTTP Request body should be included on the audit output. Default is false.
  • IncludeResponseBody: Specifies whether the HTTP Response body should be included on the audit output. Default is false.
  • IncludeOptions: Specifies which HTTP Request Options should be included in the audit output. Useful to add contextual information to the HTTP Audit Event. By default, the options are not included.
  • CreationPolicy: Allows to set a specific event creation policy. By default the globally configured creation policy is used. See Audit.NET Event Creation Policy section for more information.
  • AuditDataProvider: Allows to set a specific audit data provider. By default the globally configured data provider is used. See Audit.NET Data Providers section for more information.
  • AuditScopeFactory: Allows to set a specific audit scope factory. By default the globally configured AuditScopeFactory is used.

Output Details

The following table describes the Audit.HttpClient output fields:

HttpAction

Describes an operation call event

Field NameTypeDescription
MethodstringHTTP rest method
UrlstringRequest URL
VersionstringHttp client version
ExceptionstringException details when an exception is thrown
RequestRequestRequest audit information
ResponseResponseResponse audit information

Request

Describes a HTTP request

Field NameTypeDescription
QueryStringstringQuery string portion of the request URL
SchemestringRequest scheme (http, https)
PathstringPath portion of the request URL
HeadersDictionaryRequest headers
ContentContentRequest content

Response

Describes a HTTP response

Field NameTypeDescription
StatusCodeintResponse HTTP status code
StatusstringString representation of the response status code
ReasonstringResponse status reason phrase
IsSuccessboolIndicates if the HTTP response was successful.
HeadersDictionaryRequest headers
ContentContentRequest content

Content

Describes the content of a HTTP request or response

Field NameTypeDescription
BodystringResponse body content decoded as a string
HeadersDictionaryContent headers

Output Sample

{
	"EventType": "GET http://google.com/doesnotexists",
	"Environment": {
		"UserName": "Federico",
		"MachineName": "FEDE",
		"DomainName": "FEDE",
		"Culture": "en-US"
	},
	"StartDate": "2019-05-21T23:18:38.3251378Z",
	"EndDate": "2019-05-21T23:18:40.4623427Z",
	"Duration": 2137,
	"Action": {
		"Method": "GET",
		"Url": "http://google.com/doesnotexists",
		"Version": "1.1",
		"Request": {
			"QueryString": "",
			"Scheme": "http",
			"Path": "/doesnotexists",
			"Headers": {
				
			}
		},
		"Response": {
			"Headers": {
				"Date": "Tue, 21 May 2019 23:18:19 GMT",
				"Referrer-Policy": "no-referrer"
			},
			"Content": {
				"Body": "<!DOCTYPE html>\n<html lang=en>\n  <meta charset=utf-8>\n ....",
				"Headers": {
					"Content-Length": "1574",
					"Content-Type": "text/html; charset=UTF-8"
				}
			},
			"StatusCode": 404,
			"Status": "NotFound",
			"Reason": "Not Found",
			"IsSuccess": false
		}
	}
}

ZZZ Projects - Sponsorship

Entity Framework Extensions and Dapper Plus are major sponsors and are proud to contribute to the development of Audit.NET

Combine the power of auditing with the speed of Bulk Operations to get the best of both worlds โ€” audit and performance.

Entity Framework Extensions - Sponsor

Dapper Plus - Sponsor