c# - 由于服务生命周期问题,无法让 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 都试过了,结果相同。
解决方案
推荐阅读
- git - 如何将存储库根目录下的文件放入新目录?
- c# - 如何在 Xamarin Forms 的 Master-Detail 详细信息页面下添加网格视图?
- amazon-web-services - 无法使用公共 IP ping AWS EC2 实例
- python-3.x -
如作者所示,我们真的需要 super() 函数吗? - azure - 如何在同一 Azure VM 上托管 Web 服务器和数据库服务器
- c# - 如何使用反射获取声明的类型
- java - 基本 Java GUI 兴趣计算器中的线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常
- pandas - pandas to_parquet:在写入之前清理现有目录
- git - 使用 Git Flow 的正确流程是什么?
- r - (函数(el,elname)中的错误:“plot.title.position”不是有效的主题元素名称