You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC调用SetLockoutEndDateAsync传null解锁用户报错

报错原因

SetLockoutEndDateAsync 方法的第二个参数类型为值类型 DateTimeOffset。C# 中值类型默认不支持null值,无法直接接收null字面量,编译器无法完成null到DateTimeOffset的隐式类型转换,就会抛出这个编译错误。
ASP.NET Identity 本身的逻辑是:只要传入的锁定结束时间早于当前时间,就会判定账号未锁定,不需要依赖传null实现解锁。

修复方案

两种方案都可以解决问题,第一种兼容性更强:

  • 方案1(推荐,兼容所有ASP.NET Identity版本):传入一个早于当前UTC时间的DateTimeOffset值,明确标记账号锁定已到期,替换原有传null的代码即可:
await UserManager.SetLockoutEndDateAsync(user.Id, DateTimeOffset.UtcNow.AddMinutes(-1));
  • 方案2(仅适用于方法参数为可空类型DateTimeOffset?的高版本Identity):显式将null转换为可空DateTimeOffset类型,绕过编译类型检查:
await UserManager.SetLockoutEndDateAsync(user.Id, (DateTimeOffset?)null);

内容的提问来源于stack exchange,提问作者ELOL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 11:18:16