One of the most interesting updates of the new ASP.NET Core platform (also known as ASP.NET 5) is the fact that it merges the old MVC and Web API frameworks into one (MVC 6). This allows you to have the best of both worlds: the rich features of the former MVC Controllers – with each methods returning an ActionResult – together with the versatility of the ApiControllers, whenever we need to return pure HTTP response types such as IHttpActionResult, HttpResponseMessage and so on. This basically means being able to serve Views and/or WebServices whenever we want to, without having to change your overall approach.
What if we need to do that in a plain old ASP.NET 4 MVC-based application? As a matter of fact, we can do that there too: any standard MVC Controller can be tweaked to make it act & behave just like an ApiController: we just need to develop our very own ActionResult classes and everything will more-or-less work like we’re expecting to. However, such an approach can be very hard to maintain and test: on top of that, having MVC Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you’re not working alone.
Luckily enough, there’s a nicer alternative: we can import (and properly configure) the core ASP.NET Web API package into our MVC-based Web Application: this way we’ll get the best of both worlds, being able to use the
Controller and/or the
ApiController classes together, as long as we need to. To do that, we just have to manually install the required components of the Web API framework that we normally miss in a MVC4 or MVC5 project. This post will explain how we can do that in few easy steps.