我正在使用 ajax 在我的 web api 控制器中调用删除操作。我对使用 Ajax 调用我的 api 有两种类型有问题。
这是我的 api 代码:
[Authorize]
public class AttendancesController : ApiController
{
private readonly ApplicationDbContext _context;
public AttendancesController()
{
_context = new ApplicationDbContext();
}
[HttpDelete]
public IHttpActionResult Delete(int gigId)
{
var userId = User.Identity.GetUserId();
var attendance = _context.Attendances.SingleOrDefault(a => a.GigId == gigId && a.AttendeeId == userId);
if (attendance == null)
{
return NotFound();
}
_context.Attendances.Remove(attendance);
_context.SaveChanges();
return Ok();
}
}
当我使用此 javascript 代码时,我的操作调用,一切都很好。
$.ajax({
url: "/api/attendances/?gigId=" + button.attr("data-gig-id"),
method: "DELETE"
})
.done(function () {
button
.removeClass("btn-info")
.addClass("btn-default")
.text("Going ?");
})
.fail(function () {
alert("Something is failed!");
});
但是当我使用此代码时,我的 api 不会调用,并且会执行失败回调方法。
$.ajax({
url: "/api/attendances/" + button.attr("data-gig-id"),
method: "DELETE"
})
.done(function () {
button
.removeClass("btn-info")
.addClass("btn-default")
.text("Going ?");
})
.fail(function () {
alert("Something is failed!");
});
我很困惑,因为学习电影中使用的第二种调用方法并且有效。
你能解释一下这个问题吗?
您应该在控制器中为操作添加路由
[Route("attendances/{gigId}"(] public IHttpActionResult Delete(int gigId( { 您的代码 }
我找到了解决方案
问题在于Delete方法的定义,根据WebApiConfig.cs可接受的路由具有以下模式:api/{controller}/{id}
所以输入变量名应该是id而不是gigId。
这是正确的代码:
[HttpDelete]
public IHttpActionResult Delete(int id)
{
var userId = User.Identity.GetUserId();
var attendance = _context.Attendances.SingleOrDefault(a => a.GigId == id
&& a.AttendeeId == userId);
if (attendance == null)
{
return NotFound();
}
_context.Attendances.Remove(attendance);
_context.SaveChanges();
return Ok();
}