Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling DELETE method in Web API

In a new Web API project with :

  • GET method

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
     }
    
  • DELETE method

    // DELETE api/values/5
    public void Delete(int id)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var server = client.GetServer();
        var db = server.GetDatabase("Test");
        var collection = db.GetCollection<Entity>("Entities");
        var deleteEntity = Query<Entity>.EQ(e => e.Id, id);
        collection.Remove(deleteEntity);        
    }
    

They have a similar URL: api/values/5.

When I want to call the Delete method, it executes the Get method. What do I do?

like image 442
Tanvir Avatar asked Jan 08 '23 22:01

Tanvir


2 Answers

The URL is the same but you invoke this URL programaticaly with a "DELETE" 'http method' rather than "GET". If you are just navigating to the URL in your browser, the browser will only do a GET. How you programmatically do a DELETE (or POST or PUT) will depend on what library you are using to invoke the service but they all tend to have some kind of parameter or property called 'method' for setting this.

like image 127
Robert Levy Avatar answered Jan 11 '23 23:01

Robert Levy


Take a look at the HttpDelete attribute:

https://msdn.microsoft.com/en-us/library/system.web.mvc.httpdeleteattribute(v=vs.118).aspx

You need to decorate your methods like this so that MVC knows how to handle the incoming request:

[HttpGet]
public string Get(int id)
{
    ...
}

[HttpDelete]
public void Delete(int id)
{
    ...
}

If you're submitting to the delete method via an HTML form, bear in mind they only support the POST and GET methods, so you'll need to submit the DELETE via JavaScript:

http delete request from browser

like image 27
Rob Bell Avatar answered Jan 11 '23 22:01

Rob Bell