falah mahmood falah mahmood - 28 days ago 19
ASP.NET (C#) Question

ASP.Net Web API Action Result

I'm building an ASP.Net Web API application and i have the following code...

public IHttpActionResult GetCustomers() {
var customers = context.Customers.ToList();
return Ok(customers);
}


I'm using the Ok() method to return customers because i'm using an IHttpActionResult return type.

Now if i have the following method

public void DeleteCustomer(int id) {
var customerInDb = context.Customers.SingleOrDefault(c => c.Id == id);

if (customerInDb == null) {
NotFound();
}

context.Customers.Remove(customerInDb);
context.SaveChanges();
}


Can I use NotFound() method here when the return type of my ActionMethod is void???

Answer

Void does not have a return type. So you can try to call NotFound(), but I'm not sure if this would even compile - Haven't tried. Why don't you just go with an out of the box IHttpActionResult?

public IHttpActionResult DeleteCustomer(int id)
{
    var customerInDb = context.Customers.SingleOrDefault(c => c.Id == id);
    if (customerInDb == null)
    {
        return NotFound();
    }

    context.Customers.Remove(customerInDb);
    context.SaveChanges();

    return Ok(customerInDb);
}

Using IHttpActionResult is the more elegant version. If the id is invalid, you can just safely exit your method and tell the calling client that something went wrong. If everything went well, you're just giving the client a thumbs-up. IF you return your deleted entity or just an empty Ok() should not matter at this point.

Using void may or may not delete the entity in your data storage. The client would never know, because the server would not return any response.

Comments