Legion Legion - 2 days ago 4
AngularJS Question

Delete not working with Web Api

When I try to use the DELETE verb I either get a null parameter or the controller doesn't fire.

First I tried this:

[HttpDelete]
public IHttpActionResult Delete(Announcement announcement) {
_unitOfWork.Announcements.Remove(announcement);
_unitOfWork.Complete();
return Ok();
}


The controller fires, but
announcement
is
null
. If I check on the client side the parameter is not null, it is a properly formed object.

If I add a
Route
attribute like the below, then the controller doesn't fire at all.

[HttpDelete]
[Route("api/announcements/{announcement}")]
public IHttpActionResult Delete(Announcement announcement) {
_unitOfWork.Announcements.Remove(announcement);
_unitOfWork.Complete();
return Ok();
}


The client side is initiating the
DELETE
via angular.

myAPIservice.DeleteAnnouncement = function (announcement) {
console.log('In myAPIservice DeleteAnnouncement');
console.log(announcement);
return $http.delete(serviceURLRoot + 'api/announcements/', announcement, { withCredentials: true }).success(function (data) {
console.log('myAPIservice.DeleteAnnouncement Success');
});
};


EDIT ---

The Announcement class:

public class Announcement {
public int AnnouncementId { get; set; }
public string AnnouncementText { get; set; }
}

Answer

You can't send a 'body' with a DELETE call.

You could send the announcement id in the form of a parameter:

myAPIservice.DeleteAnnouncement = function (announcementId) {
    console.log('In myAPIservice DeleteAnnouncement');
    console.log(announcement);
    return $http.delete(serviceURLRoot + 'api/announcements/', announcementId, { withCredentials: true }).success(function (data) {
        console.log('myAPIservice.DeleteAnnouncement Success');
    });
};

Then retrieve it from your database and delete it server side:

[HttpDelete]
[Route("api/announcements/{announcementId}")]
public IHttpActionResult Delete(int announcementId) {
    var announcement = _unitOfWork.GetAnnouncementById(announcementId);

    _unitOfWork.Announcements.Remove(announcement);
    _unitOfWork.Complete();
    return Ok();
}

Or of course delete by id... whatever works.

The important part to note here is that DELETE can't carry a payload / body.

Comments