尝试激活 SecurityStampValidator 时无法解析 ISystemClock 的服务

Unable to resolve service for ISystemClock while attempting to activate SecurityStampValidator

我尝试将身份添加到我的网站 API,但出现此错误

InvalidOperationException: Unable to resolve service for type >'Microsoft.AspNetCore.Authentication.ISystemClock' while attempting to activate >'Microsoft.AspNetCore.Identity.SecurityStampValidator`1[WebAPI.Models.User>]'.

在 Startup.cs 中添加身份后,我有这个

services.AddIdentityCore<User>(options => { });
            new IdentityBuilder(typeof(User), typeof(IdentityRole), services)
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddSignInManager<SignInManager<User>>()
                .AddEntityFrameworkStores<DataContext>();

app.UseAuthentication();

用户模型 class 为空。一切都加载到数据库中。 什么东西少了?感谢您的宝贵时间和帮助。

通常在AddAuthentication调用中注册ISystemClockYou can see it in the sources here.

或者,您可以改为调用 AddDefaultIdentity,后者又会调用 AddAuthentication 本身。 Sources here.

建议您使用其中一种机制而不是 AddIdentityCore。但是,如果您出于某种原因需要调用 AddIdentityCore,那么您可以自己注册时钟:

services.TryAddSingleton<ISystemClock, SystemClock>();

不过,您还可以 运行 进入其他内容以注册上述方法处理的内容。另见 this question and its answer.

至于它是什么-ISystemClock接口是用来获取当前时间的。 SystemClock 实现从计算机获取实时时间(通过简单地调用 DateTimeOffset.UtcNow)。但是,在测试中,这允许 "fake clock" 实现传递不同的 now 值,验证闰日和其他时间业务逻辑等场景。这种模式通常称为 "virtual clock" 或 "mock the clock".