How to combine Web Api and MVC best in a single web app
asp.net-mvc-4, asp.net-web-api
Solution
I usually have another layer (which can be a different project/assembly depending on the size and complexity of your application) for my business rules. You can call this business services, or whatever works on your case.
So both MVC controllers and API controllers use this layer; which keeps the application dry.
I personally prefer to only keep complex operations in my business layers, which means if I need to read something from my persistence layer to display in my views, I do it directly on the MVC controller. This is a matter of personal preference but I prefer to go the CQRS way.
So you MVC controllers are going to instantiate these business services (or they will be injected into your controllers if you are using IoC). For read operations you can choose to go straight to your persistance layer or use another read strategy.
The same will happen to your API controllers, they will use this "common" layer of services.
You don't need to instantiate your API Controllers on your MVC Controllers. Consuming your Web Api controllers via AJAX is ok if you are developing a SPA or similar.
There is no a single way to structure your application, there are just different ways and every one has more or less pain attached.
If you are considering introducing tests in your applications (and you should :)); then you should structure it in a way it is easy to test each part of it.
Just my 2 cents.
Problem
I am about to create a simple web app and I am wondering if I should use ASP.NET MVC 4 new feature `Web API`. What's the best way to do this ? I've done some researches and I found out there are two option : `Option 1` Make the Web Api my service layer and call it from the controller to read/write data, and render the view using view models and razor. `Option 2` Make the Web Api my service layer and call it directly from the view using Javascript. I am not a big fan of `Option 2` since I feel like I am neglecting the controller which will be used only for redirection between pages. Besides I prefer using razor rather than Javascript. And If I choose `Option 1` will I have to make an instance of one Web API in the controller? because this feels like I am doing something wrong. What's the best option ? Is there any other options I haven't considered ? And if you can give some references or books which can help me, I would appreciate it. Thanks.