Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiController and Controller.

I'm little confused at what situations I can choose a particular controller.

For ex: If I want to return a view then I've to use ApiController or the ordinary Controller? I'm aware that the WCF Web API is now integrated with MVC.

Since now we can use both controllers can somebody please point at which situations to go for the corresponding controller.

share|improve this question
    
Important: ASPNET Core has 'merged' ApiController and Controller so if you're using the newer .NET you don't need to worry about ApiController anymore - docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api – Simon_Weaver Dec 30 '16 at 22:22
    
Glad they did! I predicted this long back by the way prideparrot.com/blog/archive/2012/10/asp_net_mvc_vs_webapi – VJAI Jan 1 at 8:03
up vote 234 down vote accepted

Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.

here is the link

Quote:

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.

You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.

It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.

To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.

share|improve this answer
9  
Note: since your data will be sent over the wire, how will it be formatted? The way data that an ApiController returns is formatted is determined by content negotiation, and GlobalConfiguration.Configuration.Formatters... link: blogs.msdn.com/b/kiranchalla/archive/2012/02/25/… – Tim Lovell-Smith Dec 17 '12 at 20:02
    
Is it correct to say that Web API is a common Platform for website, mobile etc? and we could use Class Library instead of Web API ? – Imad Alazani Sep 11 '13 at 6:34
    
Thanks @TimLovell-Smith for your note, because for me Andre doesn't answer the question : as a Controller can also return data, it doesn't explain why ApiController exists and is useful. – JYL Sep 11 '13 at 18:01
    
@JYL Would I be right in thinking a) ApiController doesn't let you return views? It seems clear b) ApiController is more optimized [usability, perf] for that scenario of returning data, not views. See e.g. Manish's answer. – Tim Lovell-Smith Sep 11 '13 at 20:25
2  
@JYL I augmented my answer to provide more detailed information. – Andre Loker Sep 12 '13 at 7:34

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}
share|improve this answer
1  
So nicely explained!! Thanks. – himanshupareek66 Sep 17 '15 at 10:16
2  
It's a good point but ApiController is more than just JSON serialization. It also takes care of looking at the request and returning XML if that's the accept type. – Jake Almer Mar 17 '16 at 13:32
    
If you use asp.net core, all of them are derived from Controller class. – Tân Nguyễn Sep 28 '16 at 16:59

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having 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 and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in the following post.

share|improve this answer

Use the Controller, not the ApiController.

As for the differences: Difference between Asp.net mvc apis vs asp.net web apis I think that site is being hacked at the moment. So hold off for now!

A beautiful synopsis:

  • Content negotiation
  • Flexibility
  • Separation of concerns
share|improve this answer
21  
I'm not sure if your first line is a typo but the article you link to appears to me to be about the advantages to ApiController (see also the code post by Manish Jain in this question from the same article). – grantnz Jun 4 '13 at 2:33
1  
@Pinch Your link is reported to me as malware. Is this a false positive? – ViRuSTriNiTy Jun 30 '16 at 7:12
    
@ViRuSTriNiTy thanks for the report...i updated my answer.. – Pinch Jun 30 '16 at 14:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.