CyberNinja CyberNinja - 1 month ago 5
C# Question

How do I delete a record by its primary key? using web api 2. getting 404

I'm new to using web api.. I am using some angular code. Adding and listing data works fine, but not deleting it. I tried a lot of stuff from stackoverflow add web configuration, I have my cors set to allow all site since this is just for testing.

Here's my code.. I don't what I'm missing

[HttpDelete] // I also tried HttpPut
[Route("products/RemProduct")]
public string RemoveProduct(int prodId)
{
if (prodId != null)
{
using (ProductContext dataContext = new ProductContext()) // I tried removing this using
{
// this was the my original code
//var removeProd = new ProductTest { Id = prodId };
//dataContext.ProductData.Remove(removeProd);

// used this as my alternative
dataContext.Database.ExecuteSqlCommand("DELETE FROM ProductTest where Id = " + prodId);

//dataContext.SaveChanges();
return "Product Removed";
}
}

return "Invalid";
}


This is the angular service part

this.DeleteProd = function (prodId) {
var response = $http({
method: "DELETE",
url: "https://apirepo.leofaj.org/products/RemProduct",
params: {
Id: prodId
},
// data:prodId,
//dataType:"json"
});
return response;
}


This is the web config that I tried

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"> <-- added this too.
</modules>
<security>
<requestFiltering>
<verbs>
<add verb="Delete" allowed="true" /> <<-- added this
</verbs>
</requestFiltering>
</security>
</system.webServer>


This is the error I'm getting


DELETE https://apirepo.leofaj.org/products/RemProduct?Id=13 404 ()


I really don't know why adding data is working with put then I tried put request and using the raw sql..this runs on local server.. 2 separate iis website.

Thanks

Answer

The query parameter should be named exactly as the action's argument.

url: "https://apirepo.leofaj.org/products/RemProduct", 
params: {
    prodId: prodId      // <-- Change this
},
Comments