Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve object disposed exception ASP.NET Core with Entity Framework and Identity

I am trying to write a controller that receives a request from an AJAX call and performs some calls to the database via the DBContext. However, when I place the command var user = await GetCurrentUserAsynch(); in front of any calls to the DBContext, as shown below, I get an ObjectDisposedException (Cannot access a disposed object).

It appears to be the UserManager and the DBContext not playing nicely together, however I can't find much information on the matter.

[HttpPost]        
public async void EditUserMapItemAjax([FromBody]UserMapItemViewModel userMapItemViewModel)
{            
    var user = await GetCurrentUserAsync();
    var mapItem = _db.MapItems.SingleOrDefault(x => x.Id == userMapItemViewModel.MapItemId);   

    ...
}

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
like image 444
wesley.ireland Avatar asked Dec 19 '16 19:12

wesley.ireland


1 Answers

Declare your controller action as async Task, not async void.

With the latter, as soon as your method hits the first await, it returns control to the caller, and because ASP.NET now has no way to track its progress (as it would have when it returns a Task instead), it disposes your controller instance, and (most-likely) along with it any locally-scoped fields.


While you're there, as you're in an async method anyway, you should prefer the async version of the EF call; i.e. await _db.MapItems.SingleOrDefaultAsync()

like image 78
sellotape Avatar answered Oct 14 '22 21:10

sellotape