在 ASP.NET Core 5.0 Web API 中实现 DelegatingHandler?

Implement DelegatingHandler in ASP.NET Core 5.0 Web API?

    public class AuthenticationHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage req, CancellationToken cancellationToken)
        {
            Debug.WriteLine("Process request");
            // Call the inner handler.
            var response = await base.SendAsync(req, cancellationToken);
            Debug.WriteLine("Process response");
            return response;
        }
    }

解决方案文件:https://i.stack.imgur.com/M4yv6.png

我能找到的唯一答案是针对旧版本的 Web API,其中解决方案的结构非常不同

如果您使用 DelegatingHandler 为从您的 Web API 到另一个服务的出站请求实现横切关注点,您的处理程序可以使用 HttpClientFactory 注册并附加到命名或类型化的 HttpClient:

来自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#outgoing-request-middleware-1 :

HttpClient has the concept of delegating handlers that can be linked together for outgoing HTTP requests. IHttpClientFactory:

Simplifies defining the handlers to apply for each named client.

Supports registration and chaining of multiple handlers to build an outgoing request middleware pipeline. Each of these handlers is able to perform work before and after the outgoing request. This pattern:

Is similar to the inbound middleware pipeline in ASP.NET Core. Provides a mechanism to manage cross-cutting concerns around HTTP requests, such as: caching error handling serialization logging

在这种方法下,您可以在启动时将处理程序注册到 DI 容器中,以便它附加到在您的服务某处注入或实例化时使用客户端进行的任何调用:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddTransient<AuthenticationHandler>();

    services.AddHttpClient<MyTypedHttpClient>(c =>
    {
        c.BaseAddress = new Uri("https://localhost:5001/");
    })
    .AddHttpMessageHandler<AuthenticationHandler>();
    
    // ...
}

如果您将行为附加到来自 API 消费者的 Web API 入站请求,则可以改用中间件:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0