I’ve gotten more than a few questions over the last year on how to use the ASP.NET MVC framework and the Web API framework together. Do they work together? Should they work together? When should you use one or the other?
Here’s some general rules of thumb I use.
One thing to keep in mind is that the Web API is a separate framework with its own dependency resolver, action filters, routing rules, model binding, and model serialization settings. Bringing in a 2nd set of all these components just to satisfy a few JSON requests from script is an increase in complexity.
Although the Web API does add some complexity, it is also easier to build a proper service with the Web API. I can use the verb based routing and content negotiation features to build services oriented around resources, and the OData support and automatic help page generation of the Web API framework can come in handy.
3. I’m not a big fan of services for services sake. In the previous two figures, the MVC UI and Web API pieces are drawn to suggest how they are only facades on top of a core application. Most of the interesting things are defined in the application and not in the UI and Web API layers. When someone suggests that the MVC controllers should talk over HTTP to Web API controllers in the same application, all I can think about is putting a façade over a façade, which seems silly.
There are some valid reasons to go with such an architecture (see #4), but be cautious when creating new tiers.
4. It is more than reasonable to integrate multiple applications or large pieces of functionality using services and the Web API. This is a scenario where having web service calls inside or behind the MVC controllers of an application is almost required.
The above type of scenario usually involves large applications and multiple teams. Using a service layer allows for more flexibility and scale compared to sharing binaries, or integrating at the database level (shudder with fear).
There is no quick and easy answer to the questions in this space. If you are looking for guidance, hopefully I’ve provided some rules of thumb you can use to start thinking about the answer for your specific scenario. While thinking, remember these lines from the Zen of Python:
Simple is better than complex
Complex is better than complicated