首页 > 解决方案 > 由于服务生命周期问题,无法让 Blazor WebAssembly 中的 AuthorizationMessageHandler 工作

问题描述

我无法让 AuthorizationMessageHandler 工作的 HttpClient 。

我有一个使用 Microsoft.AspNetCore.Components.WebAssembly.Authentication 包设置的项目,并为 OIDC 连接。这工作正常。现在,我想使用 OIDC 身份验证期间提供的访问令牌对另一个域中的 API 进行 http 调用。

基于https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-5.0#typed-httpclient,这应该是一个简单的任务,但我m 在服务收集方面存在各种问题。这是我必须设置类型化的 HttpClient 的内容:

builder.Services.AddScoped<AuthorizationMessageHandler>();

builder.Services.AddHttpClient<IAuthorizationClient, AuthorizationClient>(client => client.BaseAddress = new Uri(authUrl))
   .AddHttpMessageHandler(sp => sp.GetRequiredService<AuthorizationMessageHandler>().ConfigureHandler(new[] { authUrl }));

例如,这里的问题是 AuthorizationMessageHandler 在构造函数中需要一个 IAccessTokenProvider,而 Blazor 将其作为 Scoped 服务提供。但是,HttpClientFactory 注册为单例服务。当 HttpClientFactory 尝试激活 AuthorizationMessageHandler 的实例时,它失败并出现以下错误:

无法从根提供程序解析范围服务“Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler”。

将 AuthorizationMessageHandler 注册为单例,我得到:

无法使用单例“Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler”中的范围服务“Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider”。

将 AuthorizationMessageHandler 注册为瞬态,我得到:

无法从根提供程序解析“Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler”,因为它需要范围服务“Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider”。

我不知道如何让它发挥作用。上面引用的链接中的所有示例似乎都不起作用。

我已经用 net5.0 和 net6.0 都试过了,结果相同。

标签: c#asp.net-coreblazor-webassembly

解决方案


推荐阅读