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
2
Answers
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://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#outgoing-request-middleware-1 :
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:
If you’re attaching behaviors to inbound requests to your Web API from your API consumers, you can use Middleware instead: https://learn.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 configureHttpClientFactoryOptions
(minimal hosting version):