I am getting this error
System.ObjectDisposedException
HResult=0x80131622
Message=Cannot access a disposed object. A common cause of this error is dispos
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);
}
}