Choose IHttpActionResult as the response return type for your WebAPI controller methods to make your action methods easier to read, test and maintain and also abstract the way the HTTP responses are actually constructed Credit: IDG Microsoft’s WebAPI has for quite some time been the framework of choice for building RESTful services that can work over HTTP. The IHttpActionResult interface has been introduced with WebAPI version 2 and provides a different way to send back responses from your WebAPI controller methods, and it leverages async and await by default. Essentially, IHttpActionResult is a factory for HttpResponsemessage. The IHttpActionResult interface is contained in the System.Web.Http namespace and creates an instance of HttpResponseMessage asynchronously. The IHttpActionResult comprises a collection of custom in-built responses that include: Ok, BadRequest, Exception, Conflict, Redirect, NotFound, and Unauthorized. The IHttpActionResult interface contains just one method. Here’s how this interface looks: namespace System.Web.Http { public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); } } You can return a custom response using any of the helper methods of the ApiController class listed below. Ok NotFound Exception Unauthorized BadRequest Conflict Redirect InvalidModelState Returning response from WebAPI controller methods In this section we will explore how we can leverage IHttpActionResult to send back responses from the controller methods. Now, consider the following WebApi controller: public class DefaultController : ApiController { private readonly DemoRepository repository = new DemoRepository(); public HttpResponseMessage Get(int id) { var result = repository.GetData(id); if (result != null) return Request.CreateResponse(HttpStatusCode.OK, result); return Request.CreateResponse(HttpStatusCode.NotFound); } } Note that the appropriate status code is returned in each case, i.e., if data is available, HttpStatusCode.OK is returned while HttpStatusCode.NotFound is returned if data is not available. Let’s now see how the same controller method can be changed to return the response as IHttpActionResult. Here’s the updated code of the controller method for your reference. Note how HttpResponseMessage has been replaced with IHttpActionResult. public IHttpActionResult Get(int id) { var result = repository.GetData(id); if (result == null) return NotFound(); return Ok(result); } Refer to the Get method given above. The code is much simple and lean and it abstracts the way the Http message is actually constructed in the controller. And, here’s another example. Refer to the following code snippet that returns HttpResponseMessage to report success or failure. public HttpResponseMessage Delete(int id) { var status = repository.Delete(id); if (status) return new HttpResponseMessage(HttpStatusCode.OK); return new HttpResponseMessage(HttpStatusCode.NotFound); } Now see how the same action method can be refactored using IHttpActionResult to make the code much more lean and simple. public IHttpActionResult Delete(int id) { var status = repository.Delete(id); if (status) return Ok(); return NotFound(); } Which one should I use and why? So, should we use IHttpActionResult over HttpResponseMessage in our WebAPI controllers when sending back the responses? Here’s my answer to this question. I would always prefer IHttpActionResult over HttpResponseMessage as in doing so, unit testing of the controllers would become simplified. You can move the common logic for creating Http responses to other classes and make your controller methods lean and simple. In essence, the low level details of creating the Http responses would be encapsulated. On a different note, it is worth mentioning that in using IHttpActionResult, you can adhere to the Single Responsibility Principle as well as your action methods can focus on handling the Http requests rather than construct the Http response messages. There is another point worth mentioning. You can take advantage of IHttpActionResult to provide support for HTML with Razor. All you need to do is create a custom action result that can parse Razor views. Creating a custom action result is simple. You would just need to extend the IHttpActionResult interface and then implement your own version of the ExecuteAsync method. Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos