I am trying to use an HttpClient created from an IHttpClientFactory to access our Auth0 /UserInfo endpoint from a server-side controller in a Blazor WebAssembly Hosted application. (.NET 7)
In my program.cs I register the service like this:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddHttpClient("Auth0UserInfo", client => client.BaseAddress = new Uri("https://<MyAuth0Domain>/"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("Auth0UserInfo"));
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Auth0:Authority"];
options.Audience = builder.Configuration["Auth0:ApiIdentifier"];
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
I inject this into my controller like this:
public class UserController : Controller
{
private IHttpClientFactory _httpClientFactory;
private HttpClient? _httpClient;
public UserController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
//The below line is where the exception is thrown. VVVV
_httpClient = httpClientFactory.CreateClient("Auth0UserInfo");
}
//Extra code removed for clarity
}
When the above constructor is called, an IHttpClientFactory is injected as expected. In the debugger it will show that _activeHandlers on the injected object has a count of 1 and a key of "Auth0UserInfo"
However, when I try to use it to get the HttpClient instantiated, I receive a 'System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler' has been registered.'
What is wrong with how I am registering the service that is causing this exception?
Per my conversation in the comments with user u/SvdSinner:
The issue you're encountering is due to the use of BaseAddressAuthorizationMessageHandler in a server-side context. The BaseAddressAuthorizationMessageHandler is specifically designed for Blazor WebAssembly applications to automatically attach the access token to outgoing HTTP requests. When you're trying to use it in a server-side context (like in your controller), the DI container doesn't know about this handler because it's not registered for server-side scenarios.