Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

ASP.NET Core AddMvc vs AddMvcCore

Suggested Videos
Part 14 - ASP.NET Core environment variables | Text | Slides
Part 15 - ASP.NET Core MVC tutorial | Text | Slides
Part 16 - Setup mvc in core | Text | Slides

In this video we will discuss the difference between AddMvc() and AddMvcCore() methods. 

To setup MVC in an ASP.NET Core application we call AddMvc() method of the IServiceCollection interface in ConfigureServices() method of the Startup class.


In addition to AddMvc() method we also have AddMvcCore() method on the IServiceCollection interface. So, the obvious question that comes to our mind is, what's the difference between these 2 methods. 

AddMvc() v/s AddMvcCore()

Before we discuss the difference between AddMvc() and AddMvcCore() methods, let's modify the following HomeController to return JSON formatted data, instead of a simple string. 

At the moment, there is no base class specified for the the HomeController class. It works for us now because we are returning a simple string from the Index() action method.

public class HomeController
    public string Index()
            return "Hello from MVC";

However, if we want to return an HTML View or JSON data from the Index() action method, our HomeController class has to derive from the Controller class provided by the framework. The Controller base class provides support to return different results like JsonResult, ViewResult, PartialViewResult etc. Modify the HomeController class to derive from the Controller class and return JsonResult from the Index() action method as shown below.

public class HomeController : Controller
    public JsonResult Index()
        return Json(new { id=1, name="pragim" });

Please note : Controller class is present in Microsoft.AspNetCore.Mvc namespace.

At this point, run the application and we should see JSON data in the browser as expected.

Now, in the ConfigureServices() method call AddMvcCore() method instead of AddMvc() and run the application.

public void ConfigureServices(IServiceCollection services)

We get the following error
No service for type 'Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor' has been registered.

To be able to return JSON data, JsonFormatterServices need to be registered with the dependency injection container. AddMvc() method does this but not the AddMvcCore() method. You can confirm this by looking at the source code on ASP.NET Core MVC Github page. 

As the name implies, AddMvcCore() method only adds the core MVC services. On the other hand, AddMvc() method adds all the required MVC services. AddMvc() method calls AddMvcCore() method internally, to add all the core MVC services. So if we are calling AddMvc() method there is no need to explicitly call AddMvcCore() method again.

I hope this clarifies the difference between AddMvc() and AddMvcCore() methods. core tutorial for beginners