我正试图通过AJAX
调用从数据库中删除记录,如下所示:
$.ajax({
type: 'POST',
url: '/api/Person/DeletePerson',
data: { personId: personId },
contentType: 'application/json',
success: function (data) {
if (data != null) {
}
},
error: function (err, data) {
alert("Error " + err.responseText);
}
});
这是它应该输入的方法:
public void DeletePerson(int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}
但相反,它一直在输入这个方法:
public HttpResponseMessage PostPerson(dynamic person)
{
HttpResponseMessage response;
if (User.Identity.GetUserId() == null)
{
response = Request.CreateResponse(HttpStatusCode.Forbidden, "Please log in.");
}
return response;
}
两种方法都位于WebApi Controller
。
AJAX
Type: delete
不受支持。如果我使用它,我会收到此消息:
The requested resource does not support http method 'delete'
我该如何完成这项工作?
修改
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
答案 0 :(得分:0)
调用Delete方法(因为这是一个休息实现),使用DELETE动词调用/ api / Person / URL。
$.ajax({
type: 'DELETE',
url: '/api/Person',
data: { personId: personId },
contentType: 'application/json',
success: function (data) {
if (data != null) {
}
},
error: function (err, data) {
alert("Error " + err.responseText);
}
});
否则,您需要更新操作以接受带有
的删除动词[HttpDelete]
public void DeletePerson(int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}
如果要让控制器从JSON有效负载而不是请求URL中查找id,请重写如下。
public void DeletePerson([FromBody]int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}