-1

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

Happy Coconut
  • 973
  • 4
  • 14
  • 33

2 Answers2

1

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();

}
Happy Coconut
  • 973
  • 4
  • 14
  • 33
0

You can set the attached entry's state to deleted :

string userId = _User.Identity.GetUserId();
ApplicationUser loggedUser = db.Users.Find(userId);
db.Entry(loggedUser ).State = EntityState.Deleted;
db.SaveChanges();
Bikram
  • 483
  • 6
  • 16