0

I have created a Delete action method and an action button in the view, but i keep getting errors. Could someone take a look at the code and tell me what's wrong?

  public async Task<IActionResult> DeleteUserd(string Id)
    {

       //get User Data from Userid
        var user = await _usermanager.FindByIdAsync(Id);

        //List Logins associated with user
        var logins = user;

        //Gets list of Roles associated with current user
        var rolesForUser = await _usermanager.GetRolesAsync(user);

        using (var transaction = _application.Database.BeginTransaction())
        {

            if (rolesForUser.Count() > 0)
            {
                foreach (var item in rolesForUser.ToList())
                {
                    // item should be the name of the role
                    var result = await _usermanager.RemoveFromRoleAsync(user, item);
                }
            }

            //Delete User
            await _usermanager.DeleteAsync(user);

            TempData["Message"] = "User Deleted Successfully. ";
            TempData["MessageValue"] = "1";
            //transaction.commit();
        }

        return RedirectToAction("UsersWithRoles", "ManageUsers"); 
    }

Here is the view button:

 <a asp-action="DeleteUserd">Delete</a>
McGuireV10
  • 9,572
  • 5
  • 48
  • 64
LisaM
  • 21
  • 1
  • 1
  • Did you try reading the errors? – SLaks Mar 05 '18 at 20:02
  • I did.. i wouldn't be here if i understood them. Here is the error i'm getting: Controllers.AdminController+d__7.MoveNext() in AdminController.cs + var user = await _usermanager.FindByIdAsync(Id); ArgumentNullException: Value cannot be null. Parameter name: keyValues – LisaM Mar 05 '18 at 20:02
  • `Id` is probably null... The mangled code in the exception is an unfortunate side-effect of all the work the compiler does to implement `await`... – McGuireV10 Mar 05 '18 at 20:16

1 Answers1

3

Your link doesn't pass an id to delete. Hence, the action param is null and when you pass that to FindByIdAsync you get an exception because the param cannot be null.

Simplistically, you'd simply need to alter your link to:

<a asp-action"DeleteUserId" asp-route-id="@user.Id">Delete</a>

Where @user would be the particular user the delete link is for.

However, there's a number of issues with your approach here. Atomic actions such as deletions should never occur via a GET request, which a basic link always is. Instead, you use a form/AJAX and submit via POST or preferably DELETE, if you can.

You'll also need to ensure that the current user is authorized to actually delete users or you're opening yourself up to a massive disaster. Finally, you should ensure that the currently logged in user cannot delete themselves, which would obviously be problematic.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444