且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法访问已处置的对象Asp.net Identity Core

更新时间:2023-02-17 20:04:30

您是async void受害者:

[HttpPost("Create")]
public async void Create([FromBody]string employee)
{
    var user = new Employee { UserName = "test@gmail.com", Email = "test@gmail.com" };
    var d = await userManager.CreateAsync(user, "1234567");
}

您正在分派正在等待 的异步操作,并且上下文将被放置在CreateAsync中的await context.SaveChangesAsync()之前.

You are dispatching an asynchronous operation that is not being awaited, and the context will be disposed before the await context.SaveChangesAsync() in CreateAsync.

快速,明显的解决方案:

Fast, obvious solution:

[HttpPost("Create")]
public async Task Create([FromBody]string employee)
{
    var user = new Employee { UserName = "test@gmail.com", Email = "test@gmail.com" };
    var d = await userManager.CreateAsync(user, "1234567");
}

但是,您应该始终从Action返回IActionResult.这样可以更轻松地更改响应代码以及显示您的意图:

However, you should always return IActionResult from an Action. That makes it easier to change the response code as well as show your intent:

[HttpPost("Create")]
public async Task<IActionResult> Create([FromBody]string employee)
{
    var user = new Employee { UserName = "test@gmail.com", Email = "test@gmail.com" };
    var d = await userManager.CreateAsync(user, "1234567");

    if (d == IdentityResult.Success)
    {
        return Ok();
    }
    else 
    {
        return BadRequest(d);
    }
}