When to return IHttpActionResult vs Object
asp.net-web-api, c#
Solution
Returning `IHttpActionResult` provides a nice separation of concerns.
Your controller can focus on responding to the request in the most sensible manner (status codes, error messages, etc.). Another (service) layer can focus on actually retrieving and transforming the business data.
The side-effect is, your controller methods become more unit testable. Consider the following simple example:
public class MyController : ApiController
{
//or better yet, dependency-inject this
SomeService _service = new SomeService();
public IHttpActionResult Get(int id)
{
if (id < 0)
return BadRequest("Some error message");
var data = _service.GetData(id);
if (data == null)
return NotFound();
return Ok(data);
}
}
Not only is this method's logic understandable just by reading it, but you could now test the logic more easily and naturally, something like (using NUnit syntax):
[TestFixture]
public class MyControllerTests
{
[Test]
public void Get_WithIdLessThan0_ReturnsBadRequest()
{
var controller = new MyController();
int id = -1;
IHttpActionResult actionResult = controller.Get(id);
Assert.IsInstanceOf<BadRequestErrorMessageResult>(actionResult);
}
}
Similarly, you could mock the Service layer and test what happens when you give known `id` parameters to the controller, etc.
Here is a good article on Unit Testing Controllers in Web Api
Problem
In examples of using the ASP.NET Web API I see two different methods used to return data to the calling jQuery function. The first method returns an object of type `Client` but I am not sure what the second method is returning. Method #1 (returns `Client` object) ``` public IEnumerable<Client> GetAllClients() { using (var context = new PQRSModel.PQRSEntities()) { context.Configuration.ProxyCreationEnabled = false; var query = context.Clients.OrderBy(c = c.OrgName); var customers = query.ToList(); return customers; } } ``` Method #2 (What benefit does `IHttpActionResult` provide?) ``` public IHttpActionResult GetClient(int clientId) { using (var context = new PQRSModel.PQRSEntities()) { context.Configuration.ProxyCreationEnabled = false; var client = context.Clients.FirstOrDefault(c = c.ID == clientId); if (client == null) { return NotFound(); } return Ok(client); } } ``` If the second method finds a single object is there any reason it could not also return a `Client` object type?