Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Request Interception

Flux.REST provides two ways to intercept outgoing requests and incoming responses: HttpClient message handlers and Flux.REST interceptors.

Both mechanisms are configured per Flux Service and apply to requests made through every Set belonging to that Service.

HTTP Message Handler

Create a custom HTTP message handler by deriving from DelegatingHandler and overriding SendAsync:

public class CustomHttpHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        // Implement custom logic here
        return await base.SendAsync(request, cancellationToken);
    }
}

Tip

See the outgoing request middleware documentation for more information about the HttpClient handler pipeline.

Register the handler in the DI container, then configure a Flux Service to use it with UsingRest<THandler>:

services.AddFlux(flux =>
{
    flux.AddService("example-api")
        .UsingRest<CustomHttpHandler>("https://api.example.com");
});

Flux.REST Interceptor

Create a custom Flux.REST interceptor by implementing IFluxRestInterceptor and its OnRequestAsync and OnResponseAsync methods:

public sealed class CustomInterceptor : IFluxRestInterceptor
{
    public async Task OnRequestAsync(
        HttpClient client,
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        // Implement custom logic here
    }

    public async Task OnResponseAsync(
        HttpClient client,
        HttpResponseMessage response,
        CancellationToken cancellationToken)
    {
        // Implement custom logic here;
    }
}

Configure a Flux Service to use it with WithInterceptor<TInterceptor>:

services.AddFlux(flux =>
{
    flux.AddService("example-api")
        .UsingRest("https://api.example.com")
        .WithInterceptor<CustomInterceptor>();
});

Note

WithInterceptor<TInterceptor> registers the interceptor in the DI container with transient lifetime by default. Pass another ServiceLifetime as an argument when a different lifetime is required.