Suggested Videos
Part 5 - ASP.NET Web API Content Negotiation
Part 6 - ASP.NET Web API MediaTypeFormatter
Part 7 - Implementing post method in ASP.NET Web API
In this video we will discuss implementing DELETE method in ASP.NET Web API. Delete allows us to delete an item.
We want to delete the specified employee from the Employees table. Include the following Delete() method in EmployeesController.
There are 3 problems with the above code
Part 5 - ASP.NET Web API Content Negotiation
Part 6 - ASP.NET Web API MediaTypeFormatter
Part 7 - Implementing post method in ASP.NET Web API
In this video we will discuss implementing DELETE method in ASP.NET Web API. Delete allows us to delete an item.
We want to delete the specified employee from the Employees table. Include the following Delete() method in EmployeesController.
public void Delete(int id)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
entities.Employees.Remove(entities.Employees.FirstOrDefault(e => e.ID
== id));
entities.SaveChanges();
}
}
There are 3 problems with the above code
- The above code deletes the employee only when the ID of the employee that you want to delete exists.
- When the deletion is successful, since the method return type is void we get status code 204 No Content. We should be returning status code 200 OK.
- If the ID of the employee that we want to delete does not exist, there is an exception and as a result of it the Web API returns status code 500 internal server error. If an item is not found, we should be returning status code 404 Not Found.
public HttpResponseMessage
Delete(int id)
{
try
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
var
entity = entities.Employees.FirstOrDefault(e => e.ID == id);
if
(entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Employee with Id =
" + id.ToString() + " not found to
delete");
}
else
{
entities.Employees.Remove(entity);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
I am getting method not allowed error can you please help me to resolve it.
ReplyDeleteRemove authorize filter from type
DeleteI am getting HTTP/1.1 405 Method Not Allowed in fiddler
ReplyDeleteChange the type to Delete in Fiddler
DeleteChange the type to delete in Fiddler
ReplyDeleteHi, Can anyone tell how to response Bad Request in case of passing extra parameter in post API call.
ReplyDeleteExample :
{"Para1":"Value1","Para2":"Value2"} suppose this is required in my API and if I pass {"Para1":"Value1","Para2":"Value2","Para3":"Value3"} still my API working fine.
I want in above case case API should response as BAD API Call.
Please answer me ASAP.
Thanks