Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use an API Controller vs MVC Controller [closed]

I am aware of the difference between a WEB API and MVC. I am also aware that in asp.net core 1.0 there is only one type of controller that handles both MVC and API.

However, I have been watching a lot of ASP.NET MVC tutorials lately and noticed that the instructor creates an Api folder inside of the Controllers folder.

This way he splits out all of the MVC controllers which primarily deal with ViewModels and use the View function to tell MVC which view to display from the API controllers which primarily deal with Dtos and seem to strictly deal with data, not views.

You would think in an MVC application there would be no API controllers wouldn't you? Especially since in core 1.0 you inherit from one class: 'Controller'. But I guess when you incorporate front end frameworks like Angular and Kendo UI that make a lot of ajax requests you typically want to do them through api.

Here is my current understanding:
Use an MVC Controller strictly for MVC only functions like specifying which view should be displayed and passing a view model along with it.

Use an API Controller primarily for ajax calls, never for a view initial load, and never for MVC CRUD patterns.

Can someone give me a better standards to follow when it comes to this?

like image 251
Blake Rivell Avatar asked Aug 18 '16 20:08

Blake Rivell


1 Answers

As you pointed out, there is no difference in .Net Core between the two, and creating an "API" folder would be purely for project organization, but the controllers would be of the same type.

If you want a fairly simple rule, I would say that any method that returns JSON/XML/data (with no presentation information) should be an "API" controller, and anything that returns HTML should be an "MVC" controller or not inside the API folder.

like image 121
Andy Raddatz Avatar answered Oct 07 '22 07:10

Andy Raddatz