3.22请求处理程序
IHttpRequestEventHandler 接口允许您定义 HTTP 请求的预处理操作。通过实现该接口,您可以创建自定义的请求处理程序,例如 CustomRequestEventHandler 类:
IHttpRequestEventHandler 接口允许您定义 HTTP 请求的预处理操作。通过实现该接口,您可以创建自定义的请求处理程序,例如 CustomRequestEventHandler 类:
public class CustomRequestEventHandler : IHttpRequestEventHandler{ // 在发送 HTTP 请求之前的操作 public void OnPreSendRequest(HttpRequestMessage httpRequestMessage) {} // 在收到 HTTP 响应之后的操作 public Task OnPostReceiveResponseAsync(HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken) {} // 当发送 HTTP 请求发生异常时的操作 public void OnRequestFailed(Exception exception, HttpResponseMessage? httpResponseMessage = null) {}}要在应用程序中启用此处理程序,请在 Startup.cs 或 Program.cs 文件中注册 CustomRequestEventHandler 服务:
services.TryAddSingleton<CustomRequestEventHandler>();接下来,您可以在构建 HTTP 请求时指定此处理程序:
HttpRequestBuilder.Get("https://furion.net/") .SetEventHandler<CustomRequestEventHandler>();HttpRequestBuilder.Get("https://furion.net/") .SetEventHandler(typeof(CustomRequestEventHandler)); // 使用类型方式设置全局事件处理器#
除了在每个请求上单独配置,您还可以通过 HttpClientOptions 为特定 HttpClient 实例设置全局事件处理器。该处理器将对该客户端发出的所有请求生效。
// 配置默认客户端services.AddHttpClient(string.Empty) .ConfigureOptions(options => // 或使用重载:.ConfigureOptions((options, serviceProvider) => { options.HttpRequestEventHandler = new CustomRequestEventHandler(); });// 配置特定客户端services.AddHttpClient("weixin") .ConfigureOptions(options => // 或使用重载:.ConfigureOptions((options, serviceProvider) => { options.HttpRequestEventHandler = new CustomRequestEventHandler(); });