[英]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我正在尝试使用它的帖子 ID 删除帖子但每次我尝试删除帖子 400:错误请求出现在控制台中
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:这就是我的 controller 中的内容:
public IHttpActionResult Delete(int id)
{
postRepository.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
Edit: I tested the functionality using Postman.编辑:我使用 Postman 测试了功能。 Works fine
工作正常
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.您使用
DELETE
HTTP 动词发送 AJAX 请求,因此您需要在 controller 中的操作中添加[HttpDelete]
注释。 You'll also need to add the [FromUri]
annotation to the argument for the model binder to recognize and populate it.您还需要将
[FromUri]
注释添加到 model 活页夹的参数以识别和填充它。 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.请注意在
crossdomain
请求中删除了跨域属性。 It has no relevance to this logic.它与这个逻辑无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.