Home > Net >  Implement DelegatingHandler in ASP.NET Core 5.0 Web API?
Implement DelegatingHandler in ASP.NET Core 5.0 Web API?

Time:11-03

    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

CodePudding user response:

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

  • Related