没有找到HttpClient BaseAddressAuthorizationMessageHandler



我正在尝试使用本文向我的。net 5 Blazor WASM应用程序添加身份验证,但是我得到了一个错误

Unhandled exception rendering component: No service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler' has been registered.

我从git这里下载了样本,运行它,一切都工作了,然后我注意到样本是在。net 3中完成的,当我更新它运行在。net 5时,同样的错误正在悄然上升。在我的Program.cs中,我像这样注册了HttpClientBaseAddressAuthorizationMessageHandler

  public static async Task Main(string[] args)
  {
     var builder = WebAssemblyHostBuilder.CreateDefault(args);
     builder.RootComponents.Add<App>("app");
     builder.Services.AddHttpClient("ServerAPI",
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
     .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
     builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
         .CreateClient("ServerAPI"));
     builder.Services.AddBlazoredLocalStorage();
     builder.Services.AddAuthorizationCore();
     builder.Services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();
     builder.Services.AddScoped<IAuthService, AuthService>();
     await builder.Build().RunAsync();
  }

我认为这是一个错误,你可以看到我添加BaseAddressAuthorizationMessageHandler到客户端,就像它显示在这里,有什么我错过了?是否有需要导入的名称空间,或者是否缺少配置的另一部分?断点似乎在客户端的Program.cs中不起作用,我没有看到任何其他错误可以解释这一点。

一旦我弄清楚发生了什么,这是一个相当容易的修复,当授权设置像这样显然你不需要添加BaseAddressAuthorizationMessageHandler到客户端,因为这个例子是手动设置HTTP请求头通过AuthService

  public static async Task Main(string[] args)
  {
     var builder = WebAssemblyHostBuilder.CreateDefault(args);
     builder.RootComponents.Add<App>("app");
     builder.Services.AddHttpClient("ServerAPI",
        client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
     builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
         .CreateClient("ServerAPI"));
     builder.Services.AddBlazoredLocalStorage();
     builder.Services.AddAuthorizationCore();
     builder.Services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();
     builder.Services.AddScoped<IAuthService, AuthService>();
     await builder.Build().RunAsync();
  }

相关内容

  • 没有找到相关文章

最新更新