Search code examples
c#asp.netasp.net-identityasp.net-core-1.0asp.net-identity-3

Action method to delete a user with ASP.NET Identity 3.x


Here is my action method to delete a user: I feel like it is blocking since I am using user.Result to pass the actual user object from one async result to the next async method. Is there a better way to do this?

// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    var user = _userManager.FindByIdAsync(id.ToString());
    var result = await _userManager.DeleteAsync(user.Result);
    return RedirectToAction("Index");
}

Solution

  • You are correct. Using the user.Result to pass the actual object is blocking the async method.

    Best practice in using async is to use await all the way through the method. Don’t mix blocking and async code.

    // POST: Users/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id) {
        var user = await _userManager.FindByIdAsync(id.ToString());
        var result = await _userManager.DeleteAsync(user);
        return RedirectToAction("Index");
    }
    

    Source - Async/Await - Best Practices in Asynchronous Programming