Search code examples
c#asp.net-web-api2asp.net-identity

Delete user from database in Web Api 2 using Identity


What the title says. I have tried couple of methods but none of them work. If someone has some time I would really appreciate your help.

My Ajax request:

$('#deleteUserBtn').click(function () {

    $.ajax({
        url: 'Profile/DeleteUser',
        method: 'DELETE',
        headers: {
        'Authorization': 'Bearer '
            + sessionStorage.getItem("accessToken")
        },
        success: function (data) {
            sessionStorage.removeItem('accessToken');
            window.location.href = "../Login.html";
        },
        error: function (jQXHR) {
        }
    });
});

The controller is not working but it will give you idea what I am trying to do.

The controller:

[RoutePrefix("Personal_Project/Main_Page_Personal_Project")]
[Route("Profile/DeleteUser")]
[HttpDelete]
[Authorize]
public void DeleteUser()
{

   string userId = User.Identity.GetUserId();
   ApplicationUser LoggedUser = db.Users.Find(userId);

   db.Users.Remove(LoggedUser);
   db.SaveChanges();

}

I get this error in the browse console:

jquery-3.3.1.min.js:2 DELETE http://localhost:50370/Personal_Project/Main_Page_Personal_Project/Profile/DeleteUser 500 (Internal Server Error)

I visited these links but could figure out the answer. Help anyone?

Delete User - WEB API

Delete User MVC 5

Delete User MVC 5 - another likn


Solution

  • Thanks to "Dot Net Dev" I learned to use try-catch block. My inner exception suggested that I also need to remove the other table connected with foreign key with the Users table. So this is what i ended up doing:

    public void DeleteUser()
    {
         string userId = User.Identity.GetUserId();
         ApplicationUser LoggedUser = db.Users.Find(userId);
    
         db.Users.Remove(LoggedUser);
    
         AdditionalInfo info = db.AdditionalInfo.Find(userId); // Added this
         db.AdditionalInfo.Remove(info); // Added this
    
         db.SaveChanges();
    
    }