简体   繁体   中英

ASP.NET Core 6.0 - Delete from database with jQuery.ajax results in POST HTTP 400 ERROR

I started learning ASP.NET Core 6.0 a week ago. I've made a real-time chat with SignalR, I'm also saving the messages to my database.

As for now, it's just a table, each row contains in separate columns the username, message, and a delete button. I'm appending the new rows as new messages come.

The problem is that my delete button doesn't works.

In the console I'm getting a: POST https://localhost:7122/Chat/DeleteMessage/1 400 error message.

The button:

 <input type="button" onclick="Delete(@obj.Id)" value="Delete"/>

The script:

<script>
function Delete(id) {
$.ajax({
     url: "/Chat/DeleteMessage/" + id,
      type: "POST",
  })
}
</script>

And the controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteMessage(int id)
    {
        db.Chat.Remove(db.Chat.Find(id));
        db.SaveChanges();
        return RedirectToAction("Index");
    }

It's soo dumb but the problem was the [ValidateAntiForgeryToken]. I've just noticed the error in the Debug output so I removed it and now it works just fine.

Sending an AF token with the post request or removing the [ValidateAntiforgeryToken] attribute should work.

Can you check the network tab in the developer tool and how the request is going and its response? you can also test the url on the postman

You can also try to add AntiForgoryToken into ajax header. Here is a demo:

@Html.AntiForgeryToken()

js:

<script>
function Delete(id) {
$.ajax({
     url: "/Chat/DeleteMessage/" + id,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
      type: "POST",
  })
}
</script>

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