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

℡╲_俬逩灬. 提交于 2019-12-07 03:53:52

问题


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



来源:https://stackoverflow.com/questions/41229637/how-to-resolve-object-disposed-exception-asp-net-core-with-entity-framework-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!