为什么我的 Blazor 项目不能正确使用 MyProj.HttpApi.Client?

Why could not my Blazor project consume MyProj.HttpApi.Client correctly?

我使用 ABP CLI 生成了一个 MVC 模板,我想用它来尝试 Blazor Server 项目。我确实添加了一个 MyProjBlazorModule,它与每个通用模块相同,就像 ConsoleTestApp 项目 所做的那样:

namespace MyProj.Blazor
{
    [DependsOn(
        typeof(MyProjHttpApiClientModule),
        typeof(AbpHttpClientIdentityModelModule)
        )]
    public class MyProjBlazorModule : AbpModule
    {
    }
}

然后我将模块作为服务添加到 ConfigureServices 方法:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSyncfusionBlazor();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddApplication<TaurusBlazorModule>();

    }

为了快速测试,我还从模板项目 MyProj.HttpApi.Client.ConsoleTestApp 复制了 ClientDemoService class ,然后我像这样在我的 index.razor 中使用它:

@inject ClientDemoService _clientService
...
protected override async Task OnInitializedAsync()
{

    await base.OnInitializedAsync();
    profile = await _clientService.RunAsync();
}

但是无法运行,在浏览器中显示错误消息:

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).

而如果我像这样复制与控制台测试项目相同的代码:

        using (var application = AbpApplicationFactory.Create<MyProjConsoleApiClientModule>())
        {
            application.Initialize();

            var demo = application.ServiceProvider.GetRequiredService<ClientDemoService>();
            profile = AsyncHelper.RunSync(() => demo.RunAsync());

        }

它奏效了。我想知道使用 ABP 模块和在这里显式调用一个丑陋的 ServiceProvider 方法之间的区别,我怎样才能以一些正确和漂亮的方式解决这个问题?

感谢大家的帮助!

我终于明白了。在来自 abp CLI 的模板源代码中,MyProjHttpApiHostModule 的 ConfigureAuthentication 方法像这样注册身份验证服务:

    private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
    {
        context.Services.AddAuthentication()
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.ApiName = "MyProj";
                options.JwtBackChannelHandler = new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                };
            });
    }

其中 AddAuthentication() 方法使用了空参数 重载,导致 未指定 authenticationScheme 错误。我参考了 IdentityServer4 official document 并找到了正确的方法:

context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                ...
            });

这很简单,我应该设置默认方案JwtBearerDefaults.AuthenticationScheme 正如错误报告的那样,使用不同的 AddAuthentication 方法重载。

我希望这篇 post 可以帮助面临相同或相似问题的人。