Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI Controller is not being reached on DELETE command

Tags:

I am having difficulty getting the DELETE Method on my Controller to fire when submitting the request over ASP.NET Web API. It returns a 404 but I cannot figure out why. The GET & POST requests work as expected, returning both a list of items as well as a single item when provided an id, but when I call the API using a DELETE request I get a 404 ERROR.

Scenario:

1. ASP.NET Web Forms application ...

Not an MVC application although I have installed the MVC4 package in order to leverage the Web API features.

2. Route Table definition in global.asax

            RouteTable.Routes.MapHttpRoute(

                    "Default", 
                    "api/{controller}/{id}", 
                    new { id = RouteParameter.Optional } 
            );

3. Controller definition

    public HttpResponseMessage<Customer> Post(Customer customer)
    {
        CustomerDb.Customers.AddObject(customer);
        CustomerDb.SaveChanges();
        var response = new HttpResponseMessage<Customer>(customer, HttpStatusCode.Created);
        response.Headers.Location = new Uri(Request.RequestUri, "/api/Customer/"+customer.id.ToString());
        return response;
    }

    public CustomerDTO Get(int id)
    {
        CustomerDTO custDTO = null;
        Customer cust = CustomerDb.Customers.Where(c => c.id == id).SingleOrDefault();
        if (cust == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        else
            custDTO = new CustomerDTO(cust);
        return custDTO;
    }

    public IEnumerable<CustomerDTO> Get()
    {
        IQueryable<Customer> custs = CustomerDb.Customers.AsQueryable();

        List<CustomerDTO> dto = new List<CustomerDTO>();
        foreach (Customer cust in custs)
        {
            dto.Add(new CustomerDTO(cust));
        }

        return dto;
    }

    public Customer Delete(int id)
    {
        Customer cust = CustomerDb.Customers.Where(c => c.id == id).SingleOrDefault();
        if (cust == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);

        CustomerDb.Customers.DeleteObject(cust);
        CustomerDb.SaveChanges();
        return (cust);
    }

I have some of the methods throwing a BadRequest error instead of a 404 when a customer cannot be found so I don't get these responses confused with the REAL problem. Obviously in a real implementation a no customer would return a 404 error.

4. Ajax Call via JQuery to delete item.

function deleteCustomer(id) {

        var apiUrl = "/api/customer/{0}";
        apiUrl = apiUrl.replace("{0}", id);

        $.ajax({
            url: apiUrl,
            type: 'DELETE',
            cache: false,
            statusCode: {
                200: function (data) {
                }, // Successful DELETE
                404: function (data) {
                    alert(apiUrl + " ... Not Found");
                }, // 404 Not Found
                400: function (data) {
                    alert("Bad Request O");
                } // 400 Bad Request
            } // statusCode
        }); // ajax call
    };

SO I am expecting that the singel route map should accomodate ALL the scenarios ...

  1. GET api/customer -- Returns ALL customers
  2. GET api/customer/5 -- Returns the customer whose ID = 5
  3. POST api/customer -- Creates a new customer record
  4. DELETE api/customer/5 -- Deletes the customer whose ID = 5

1,2 & 3 work without a problem, just the DELET does not work. I have tried MANY iterations and different tweaks, to no avail. I still feel however that I am overlooking something small. I feel like the problem must be around theRoute mapping but I don't see why this route would not succesfully handle the DELETE request.

Any help would be greatly appreciated.

Thank You!

Gary

like image 990
Gary O. Stenstrom Avatar asked Mar 13 '12 21:03

Gary O. Stenstrom


People also ask

How do you delete in Web API?

Here, we will implement Delete action method in the Web API. The HTTP DELETE request is used to delete an existing record in the data source in the RESTful architecture. So let's create an action method in our StudentController to delete an existing student record in the database using Entity Framework.

What is Delete method in API?

The Delete method requests the server to delete the resource identified by the request URI. The resource deletion depends on the server and is deleted if prescribed for deletion.

How do I find my controller name on Web API?

Look in the route dictionary for the key "controller". Take the value for this key and append the string "Controller" to get the controller type name. Look for a Web API controller with this type name.

How do I set up a new API controller?

In Solution Explorer, right-click the Controllers folder. Select Add, then select Controller. In the Add Scaffold dialog, select "Web API 2 Controller with actions, using Entity Framework". Click Add.


1 Answers

Do you have this defined in your web.config?

   <system.webServer>
          <modules runAllManagedModulesForAllRequests="true">
          </modules>
    </system.webServer>
like image 67
Dave Bettin Avatar answered Oct 10 '22 12:10

Dave Bettin