简体   繁体   中英

Should I check if a user exists before deleting it?

I saw many times code like this:

var user = await _userManager.FindByNameAsync(username);
var result = await _userManager.DeleteAsync(user);

return new JsonResult(result);

But I would like to know your opinion if this is good or is better to do if statement where you check if user really exist or not?

That depends upon _userManager.DeleteAsync implementation, since you are using .Net Core Identity, implementation of DeleteAsync method will throw ArgumentNullException

You can check source code here , and here is method's implementation:

public virtual Task<IdentityResult> DeleteAsync(TUser user)
    {
        ThrowIfDisposed();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return Store.DeleteAsync(user, CancellationToken);
    }

The answer depends on the context in which the deletion is performed:

  • If your program is in an active interaction with an end-user who requests user deletion, then knowing that the user he wanted to delete did not exist is a valuable piece of information, so you should report it.
  • If your program executes a batch clean-up of some sort, and the situation when a user may or may not exist is fine, then you could skip the check.

Note your code would end up checking user for null anyway to avoid ArgumentNullException in the call of DeleteAsync . That's only an implementation detail: the real decision that you need to make is what to do about it.

Note: this answer assumes you are using the built-in UserManager and not a custom one.

As you can see in the source code :

public virtual Task<IdentityResult> DeleteAsync(TUser user)
{
    ThrowIfDisposed();
    if (user == null)
    {
        throw new ArgumentNullException(nameof(user));
    }

    return Store.DeleteAsync(user, CancellationToken);
}

Passing null as a parameter to DeleteAsync would throw an ArgumentNullException . So, no, the code you provided is not correct. You need to check whether the user exists in the first place:

var user = await _userManager.FindByNameAsync(username);

if (user == null)
{
    return BadRequest("User not found");
}

var result = await _userManager.DeleteAsync(user);

return Json(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM