How to resolve object disposed exception ASP.NET C

2019-04-29 21:05发布

问题:

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

回答1:

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()