A free and open-source web framework that enables developers to create web apps using C# and HTML, developed by Microsoft.
SecureHttpDelegateHandler can only be constructed if all of its constructor parameters are registered in the DI container before the handler itself is registered. The error indicates that AuthService (and possibly TokenStorage) is not resolvable when the handler is created.
In Blazor WebAssembly, DelegatingHandler-based token handlers are typically wired using AuthorizationMessageHandler / BaseAddressAuthorizationMessageHandler and IAccessTokenProvider, but the same DI rules apply: every dependency in the handler constructor must be registered.
Key points for the shown setup:
- Register dependencies before the handler
- Ensure the handler is registered with the correct lifetime
- Ensure the named
HttpClientis created correctly
A corrected ordering for the registrations would look like this:
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// Base HttpClient (if needed)
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com")
});
// Register services used by the handler FIRST
builder.Services.AddScoped<TokenStorage>();
builder.Services.AddScoped<AuthService>();
// Now register the handler that depends on TokenStorage and AuthService
builder.Services.AddTransient<SecureHttpDelegateHandler>();
// Register the named HttpClient that uses the handler
builder.Services.AddHttpClient("XXXAPI", httpClient =>
{
httpClient.BaseAddress = new Uri("https://jsonplaceholder.typicode.com");
})
.AddHttpMessageHandler<SecureHttpDelegateHandler>();
// Other app services
builder.Services.AddScoped<AuthenticationStateProvider, AppAuthenticationStateProvider>();
builder.Services.AddScoped<PostService>();
// Factory-based client for injection
builder.Services.AddScoped(sp =>
sp.GetRequiredService<IHttpClientFactory>().CreateClient("XXXAPI"));
builder.Services.AddAuthorizationCore();
var app = builder.Build();
await app.RunAsync();
Notes:
-
AuthServicemust be registered (AddScoped<AuthService>()or similar) with the same or longer lifetime than the handler’s dependencies. - The handler’s constructor can then safely be:
public SecureHttpDelegateHandler(TokenStorage tokenStorage, AuthService auth) { _tokenStorage = tokenStorage; _auth = auth; } - When using Blazor WebAssembly with JWTs, consider using
AuthorizationMessageHandlerandIAccessTokenProvideras described in the Blazor WebAssembly additional security scenarios. These are designed to attach tokens to outgoing requests and handle token acquisition/refresh.
References: