IHttpActionResult in WebAPI

IHttpActionResult  is an interface which was introduced in WebAPI 2.It is used to create HttpResponseMessage which is one of the return types in WebAPI.

Use of IHttpActionResult

Using IHttpActionResult  to return HttpResponseMessage object instead of directly returning the HttpResponseMessage object has the following advantages:

Since we return an interface from the action method ,it makes it easier to unit test our action methods.

It promotes separation of concerns since the logic to create the HttpResponseMessage object is moved to different class.This class implements the IHttpActionResult  interface.

We can use the above HTMLResponse  as:

So as you can see in the above Get method ,it just creates an instance of HTMLResponse  and returns it.This makes the Get method cleaner since the responsibility of creating HTMLResponse  object is moved to separate class.

System.Web.Http.Results namespace

System.Web.Http.Results namespace contains different implementations of the IHttpActionResult  interface.For example JsonResult<T> is a generic class which is used to return JSON data and status code of OK.

ApiController class defines several helper methods which can be used to create implementations of IHttpActionResult  interface.

For example the following will return the generic Json<T> object.




You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *