Cannot access a disposed object. A common cause of this error is disposing a context

This is because of your method return type async void. In general, when you are using async void in your code it’s bad news, because:

  • You can’t wait for its completion
  • Any unhandled exceptions will terminate your process (ouch!)

So return async Task instead of async void from your method as follows:

public async Task OnGet(int id)
{
    Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);

    if(Book == null)
    {
       RedirectToPage("Index");
    }
}

For more details:

  • C# – beware of async void in your code

  • Cannot access a disposed object in ASP.NET Core when injecting DbContext


What I am about to post is NOT the answer to this particular question. But it is related so just to save somebody headache I am posting it. I was encountering this same error

System.ObjectDisposedException: Cannot access a disposed object. etc

The following was the code with the bug (can you see it?):

[HttpGet("processs/oxxo-spei/ticket-email/{paymentIdx}")]
public StatusCodeResult ProcessOxxoSpeiTicketEmailAsync(string paymentIdx)
{
    var paymentId = paymentIdx.DecodeRef();
            
    var response = _orderEngine.ProcessOxxoSpeiTicketEmailAsync(paymentId);

    return StatusCode(200);
}

The following change fixed it:

[HttpGet("processs/oxxo-spei/ticket-email/{paymentIdx}")]
public async Task<StatusCodeResult> ProcessOxxoSpeiTicketEmailAsync(string paymentIdx)
{
    var paymentId = paymentIdx.DecodeRef();
            
    var response = await _orderEngine.ProcessOxxoSpeiTicketEmailAsync(paymentId);
                // ^^^^I HAD FORGOTTEN TO PUT AWAIT
    return StatusCode(200);
}

Yes that's right I had forgotten to put "await" before a function that used an EF Core dbcontext. Adding 'await' fixed it. So easy to miss it, especially if you're tired and under deadline.