InvalidOperationException: 无法创建类型 'Microsoft.AspNetCore.Identity.UserManager 的实例

InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.Identity.UserManager

我打算在.net core mvc 中登录后获取用户数据,但是出现了这个错误,这是什么?以及如何解决?

InvalidOperationException:无法创建类型 'Microsoft.AspNetCore.Identity.UserManager`1[[Microsoft.AspNetCore.Identity.IdentityUser, Microsoft.Extensions.Identity.Stores, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]' 的实例。模型绑定的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。记录类型必须有一个主构造函数。或者,给 'userManager' 参数一个非空的默认值。

    private UserManager<ApplicationUser> _userManager;
    public void HomeController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> MySchedule(UserManager<IdentityUser> userManager)
    {
        var CourseChosen = from m in _context.CourseChosen
                               select m;
        var userid = _userManager.GetUserId(HttpContext.User);
        if (userid == null)
        {
            return RedirectToAction("Login", "Account");
        }
        else
        {
            ApplicationUser user = await _userManager.GetUserAsync(User);
            var identification = user.StudentId;
            CourseChosen = CourseChosen.Where(x => x.StudentId == identification);

            var coursechosen = new MyCourse
            {
                MyCourses = await CourseChosen.ToListAsync()
            };

            return View(coursechosen);
        }
    }

InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.Identity.UserManager`1[[Microsoft.AspNetCore.Identity.IdentityUser, Microsoft.Extensions.Identity.Stores, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Record types must have a single primary constructor. Alternatively, give the 'userManager' parameter a non-null default value.

此错误是由于在 MySchedule 操作中使用 UserManager<IdentityUser> userManager 作为参数造成的。

只需更改:

public async Task<IActionResult> MySchedule(UserManager<IdentityUser> userManager)

收件人:

public async Task<IActionResult> MySchedule()

如何DI UserManager,应该是:

public class HomeController : Controller
{
    private readonly UserManager<IdentityUser> _userManager;

    //Constructor name should be the same as the class
    public HomeController(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }
    //action below..
    //request url should be: Home/MySchedule if you use MVC

    public async Task<IActionResult> MySchedule()
    {....}
}