Search code examples
blazorblazor-webassembly

How can I add HTTP interceptors in Blazor WASM?


In Angular, there is the HTTP interceptor functionality. How can I achieve the same in Blazor WASM?

HTTP interceptors

(order of the interceptors are important)


Solution

  • You can use delegating handlers. Create a new class extending DelegatingHandler:

    public class MyDelegatingHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // before request
            
            var response = await base.SendAsync(request, cancellationToken);
            
            // after request
        }
    }
    

    Then register it in Program.cs:

    using Microsoft.Extensions.DependencyInjection;
    ...
    
    builder.Services.AddTransient<MyDelegatingHandler>();
    
    builder.Services
        .AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
        .AddHttpMessageHandler<MyDelegatingHandler>();
    

    Documentation

    From documentation:

    Multiple handlers can be registered in the order that they should execute. Each handler wraps the next handler until the final HttpClientHandler executes the request:

    using Microsoft.Extensions.DependencyInjection;
    ...
    
    builder.Services.AddTransient<SampleHandler1>();
    builder.Services.AddTransient<SampleHandler2>();
    
    builder.Services.AddHttpClient("MultipleHttpMessageHandlers")
        .AddHttpMessageHandler<SampleHandler1>()
        .AddHttpMessageHandler<SampleHandler2>();
    

    In the preceding code, SampleHandler1 runs first, before SampleHandler2.