6.46HTTP Request Pipeline Handler
The HTTP request pipeline handler is the core mechanism by which the framework sends HTTP remote requests; the final execution logic that actually issues the request is completed through the collaboration of this series of handlers. Almost all key features—such as automatic redirects, request analysis, timeout management, retry policies, exception suppression, request assertions, and automatic Access Token management—are each implemented by an independent pipeline handler. Each handler focuses on a single responsibility, making it easy to extend and maintain.
To customize a pipeline handler, simply implement the IHttpRequestPipelineHandler interface. For example, the following example implements a simple printing handler that outputs logs before and after a request:
internal sealed class PrintPipelineHandler : IHttpRequestPipelineHandler{ /// <inheritdoc /> public async Task<HttpResponseMessage?> HandleAsync(HttpRequestPipelineContext context, Func<Task<HttpResponseMessage?>> next) { Console.WriteLine("Before the request"); // Call the next handler's delegate var httpResponseMessage = await next(); Console.WriteLine("Response received"); return httpResponseMessage; }}Then, when configuring the HttpRemote service in Startup.cs or Program.cs, register the handler via AddPipelineHandler to enable it:
services.AddHttpRemote(builder =>{ builder.AddPipelineHandler<PrintPipelineHandler>();});After registration, each remote request prints "Before the request" before being sent and prints "Response received" after receiving a response, allowing you to observe the request lifecycle intuitively.
HttpRequestPipelineContext contains the following properties:
- Properties:
OriginalBuilder: The originalHttpRequestBuilder(HttpRequestBuildertype).Builder: The currently usedHttpRequestBuilder(HttpRequestBuildertype).HttpClient: TheHttpClientinstance (HttpClienttype).CompletionOption: Indicates how the response content is handled (HttpCompletionOptiontype).CancellationToken: The currently effective cancellation token (CancellationTokentype).SendAsync: The send delegate (Func<HttpClient, HttpRequestMessage, HttpCompletionOption, CancellationToken, Task<HttpResponseMessage>>type). The delegate that actually issues theHTTPrequest.RequestMessage: The most recently builtHttpRequestMessage(HttpRequestMessage?type).ResponseMessage: The most recently builtHttpResponseMessage(HttpResponseMessage?type).RequestDuration: The request duration (milliseconds) (longtype).Items: The shared data dictionary (IDictionary<object, object?>type)
To learn about all of the built-in request pipeline handlers in the framework, refer to the repository source code: https://github.com/monksoul/HttpAgent/tree/master/src/HttpAgent/src/Pipelines/Handlers