Monday, December 22, 2014

Difference between ApiController and Controller in ASP.NET MVC

In Today's generation all the peoples are very smart. They are using mobiles, tablets etc. device in those days rather than browser and these device have unlimited apps for make a life smooth. At the end, we all are moving from the web world towards the app world.


So, why not we will develop a worth program which will be helpful in both web and app world.
So, For that i suggest go through ApiControllers.

Difference :

1) You can use controller to render your normal views only.
but using the ApiController action only returns the data which is serialized and sent to client.
So, that you can use it any Html based application.

2) You can self hosting using ApiController but not from MVC Controllers.

3) If you are aware with ASP.NET MVC then you are already knows about the controllers.
And the APIControllers are same as MVC controllers, but it inherits the ApiController class instead of the Controller class.

4)  APIControllers is a lightweight architecture excepting the web Apps.

5)  MVC Controller shows the URL Samples matching the default route pattern"{controller}/{action}/{id}". and the ApiController shows "api/{controller}/{id}".

6) Web API Supports the self hosting, content negotiation where the MVC doesn't support it.

7) Use Controller when - If you're writing an HTML based web/internet application (with the occasional AJAX call returning json here and there).
Use ApiControllers When - If you want to provide a data driven/REST-ful interface to a system.

8) For Example,
     //In ASP.NET MVC
     public class PostsController : Controller
     {
         // GET: /Tweets/
         [HttpGet]
         public ActionResult Index() {
               return Json(Facebook.GetAllPosts(), JsonRequestBehavior.AllowGet);
         }
     }

     //ASP.NET Web API
public class TweetsController : ApiController { // GET: /Api/Tweets/ public List<Posts> GetAllPosts() { return Facebook.GetAllPosts(); } }
So, You have to use the API which is compatible with the browsers and all the modern devices apps.
Actually, the Web API is a open source platform for building a REST-ful services over the .Net Framework.  



Now, I hope you have got when to use Web API over MVC and how it works.
Please keep commenting every author needs motivation.

0 comments:

Post a Comment