3.49Setting the request event handler
Created on Aug 17, 2026~3 min read
The IHttpRequestEventHandler interface allows you to define pre-processing operations for HTTP requests. By implementing this interface, you can create a custom request event handler, such as the CustomRequestEventHandler class:
public class CustomRequestEventHandler : IHttpRequestEventHandler{ // Operation before sending the HTTP request public void OnPreSendRequest(HttpRequestMessage httpRequestMessage) {} // Operation after receiving the HTTP response public Task OnPostReceiveResponseAsync(HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken) {} // Operation when an exception occurs while sending the HTTP request public void OnRequestFailed(Exception exception, HttpResponseMessage? httpResponseMessage = null) {}}To enable this handler in your application, register the CustomRequestEventHandler service in the Startup.cs or Program.cs file:
services.TryAddSingleton<CustomRequestEventHandler>();Next, you can specify this handler when building the HTTP request:
HttpRequestBuilder.Get("https://furion.net/") .SetEventHandler<CustomRequestEventHandler>();HttpRequestBuilder.Get("https://furion.net/") .SetEventHandler(typeof(CustomRequestEventHandler)); // Set using the type approachGlobal Event Handler
In addition to configuring each request individually, you can also set a global event handler for a specific HttpClient instance via HttpClientOptions. This handler takes effect for all requests issued by that client.
// Configure the default clientservices.AddHttpClient(string.Empty) .ConfigureOptions(options => // or use the overload: .ConfigureOptions((options, serviceProvider) => { options.HttpRequestEventHandler = new CustomRequestEventHandler(); });// Configure a specific clientservices.AddHttpClient("weixin") .ConfigureOptions(options => // or use the overload: .ConfigureOptions((options, serviceProvider) => { options.HttpRequestEventHandler = new CustomRequestEventHandler(); });