Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to return IHttpActionResult vs Object

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?

like image 485
webworm Avatar asked May 30 '14 18:05

webworm


People also ask

When should I use IHttpActionResult?

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

What is the difference between IHttpActionResult and IActionResult?

What is the difference between IHttpActionResult and IActionresult ? "IActionResult is the new abstraction that should be used in your actions. Since Web API and MVC frameworks have been unified in ASP.NET Core, various IActionResult implementations can handle both traditional API scenarios.".

What does IActionResult return?

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.


2 Answers

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

like image 139
kaveman Avatar answered Sep 20 '22 05:09

kaveman


The second method allows you to return just status codes (like the 404 in the example), streaming file content and other types of non-object content.

like image 34
Dmitry S. Avatar answered Sep 23 '22 05:09

Dmitry S.