Getting 400: Bad Request on delete request using asp.net

I’m trying to delete a post using it’s post ID
But every time I try to delete a post 400:bad request shows up in the console

var deletepost=function(deleteid){
    $.ajax({
        
        url:"http://localhost:12091/api/post/"+deleteid,
        method: "DELETE",
        header:"Content-Type:application/json",
        crossdomain: true,
        complete:function(xmlhttp, status){
            if(xmlhttp.status == 200)
            {
                alert("Post Deleted");
            }
            else{
                console.log(xmlhttp.status+":"+xmlhttp.statusText);
                console.log("unsuccessful");
            }
        }
        
    })
}

This is what I have in my controller:

    public IHttpActionResult Delete(int id)
    {
        postRepository.Delete(id);
        return StatusCode(HttpStatusCode.NoContent);
    }

Edit: I tested the functionality using Postman. Works fine

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re sending the AJAX request using a DELETE HTTP verb, so you need to add the [HttpDelete] annotation to the action in your controller. You’ll also need to add the [FromUri] annotation to the argument for the model binder to recognize and populate it. Try this:

var deletepost = function(deleteid) {
  $.ajax({
    url: "http://localhost:12091/api/post/" + deleteid,
    method: "DELETE",
    header: "Content-Type:application/json",
    complete: function(xmlhttp, status) {
      if (xmlhttp.status == 200) {
        alert("Post Deleted");
      } else {
        console.log(xmlhttp.status + ": " + xmlhttp.statusText);
        console.log("unsuccessful");
      }
    }
  })
}
[HttpDelete]
public IHttpActionResult Delete([FromUri]int id) 
{
  postRepository.Delete(id);
  return StatusCode(HttpStatusCode.NoContent);
}

Note the removal of the crossdomain property in the AJAX request. It has no relevance to this logic.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x