Cannot access a disposed object Asp.net Identity Core

前端 未结 1 1898
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 02:52

I am getting this error

System.ObjectDisposedException
  HResult=0x80131622
  Message=Cannot access a disposed object. A common cause of this error is dispos         


        
1条回答
  •  囚心锁ツ
    2021-01-05 03:14

    You are an async void victim:

    [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");
    }
    

    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");
    }
    

    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 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);
        }
    }
    

    0 讨论(0)
提交回复
热议问题