简体   繁体   中英

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;
        }
    }

Solution Files: https://i.stack.imgur.com/M4yv6.png

The only answers i can find are for older versions of Web API, where the structure of the solutions was very different

If you're using a DelegatingHandler to implement cross-cutting concerns for outbound requests from your Web API to another service, your handler can be registered and attached to a named or typed HttpClient using HttpClientFactory:

From 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

Under this approach, you can register the handler in your startup into the DI container so that its attached to any calls made using the client when its injected or instantiated somewhere in your service:

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

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

If you're attaching behaviors to inbound requests to your Web API from your API consumers, you can use Middleware instead: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

If you are using IHttpClientFactory and want to define handler for all clients created by it you can configure HttpClientFactoryOptions (minimal hosting version):

builder.Services.AddScoped<RequestDelegatingHandler>();
builder.Services.ConfigureAll<HttpClientFactoryOptions>(options =>
{
    options.HttpMessageHandlerBuilderActions.Add(builder =>
    {
        builder.AdditionalHandlers.Add(builder.Services.GetRequiredService<RequestDelegatingHandler>());
    });
});

public class RequestDelegatingHandler : DelegatingHandler
{
   // implementation
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM