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

Hil*_*lls 3 c# asp.net-core-webapi asp.net-core-identity

我尝试将 Identity 添加到我的 Web API,但收到此错误

InvalidOperationException:尝试激活 >'Microsoft.AspNetCore.Identity.SecurityStampValidator`1[WebAPI.Models.User>]' 时无法解析类型 >'Microsoft.AspNetCore.Authentication.ISystemClock' 的服务。

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

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

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

usermodel 类是空的。一切都加载到数据库中。有什么不见了?我感谢您的时间和帮助。

Mat*_*int 13

ISystemClock通常在登记AddAuthentication电话。 您可以在此处的来源中看到它。

或者,您可以改为调用AddDefaultIdentity,而后者又会调用AddAuthentication自身。 来源在这里。

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

services.TryAddSingleton<ISystemClock, SystemClock>();
Run Code Online (Sandbox Code Playgroud)

但是,您可能还会遇到其他事情来注册上述方法处理的事情。另请参阅此问题及其答案

至于它是什么 - 该ISystemClock界面用于获取当前时间。该SystemClock实现从计算机获取实时时间(通过简单地调用DateTimeOffset.UtcNow)。但是,在测试中,这允许“假时钟”实现传入不同的 now 值,验证闰日等场景和其他时间业务逻辑。这种模式通常被称为“虚拟时钟”或“模拟时钟”。