Understanding the Difference Between AddMvc and AddMvcCore in ASP.NET Core
When it comes to setting up the Model-View-Controller (MVC) framework in an ASP.NET Core application, two methods are commonly used: AddMvc and AddMvcCore. But what’s the difference between them? In this article, we’ll delve into the world of ASP.NET Core and explore the relationship between these two methods.
Setting Up MVC in ASP.NET Core
To set up MVC in an ASP.NET Core application, we use the AddMvc method in the Startup class. This method is called on the IServiceCollection interface in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
The AddMvcCore Method
In addition to AddMvc, we have the AddMvcCore method on the IServiceCollection interface. This method adds only the core MVC services, leaving out some of the features provided by AddMvc.
The Difference Between AddMvc and AddMvcCore
So, what’s the difference between these two methods? To answer this question, let’s modify the HomeController to return data in JSON format instead of a simple string. At present, the HomeController class doesn’t inherit from the Controller base class, so it can only return a simple string from the Index action method:
public class HomeController
{
public string Index()
{
return "Hello from MVC";
}
}
However, if we want the Index method to return HTML view or JSON data, our HomeController class must inherit from the Controller class, which provides support for returning different results, such as JsonResult, ViewResult, and PartialViewResult:
public class HomeController : Controller
{
public JsonResult Index()
{
return Json(new { id = 1, name = "pragim" });
}
}
Running the Application with AddMvcCore
Now, let’s call AddMvcCore in the ConfigureServices method instead of AddMvc and run the application:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
We get an error: “Not registered as ‘Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor’ type of service.” This is because AddMvcCore doesn’t register the JsonFormatter in the container, which is necessary to return JSON data.
The Relationship Between AddMvc and AddMvcCore
As the name suggests, AddMvcCore method adds only the core MVC services. On the other hand, AddMvc method adds all the required MVC services. In fact, AddMvc method is called internally to add all core MVC services. Therefore, if we call AddMvc, we don’t need to explicitly call AddMvcCore method.
In conclusion, AddMvc and AddMvcCore are two methods used to set up MVC in an ASP.NET Core application. While AddMvcCore adds only the core MVC services, AddMvc adds all the required MVC services.