0

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; }
}
Legion
  • 3,922
  • 8
  • 51
  • 95

1 Answers1

2

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.

Alex
  • 37,502
  • 51
  • 204
  • 332
  • That's unfortunate because it means I have to fetch the object from the database before I can remove it (because of Entity Framework). Is it common to replace DELETE calls with POSTs to avoid the extra round trip? – Legion Dec 01 '16 at 16:15
  • 1
    NO don't do a post to delete! Check this out - http://stackoverflow.com/questions/2471433/how-to-delete-an-object-by-id-with-entity-framework – Alex Dec 01 '16 at 16:26