ASP.NET Core AddMvc() Vs AddMvcCore()

Scenario : In Asp.Net core we can leverage the advantages of MVC like routing,razors etc by injecting the Mvc dependency in the Startup.cs like shown below



But when you notice closely we see following ambiguity , AddMvc() and why not AddMvcCore() ??



                                                         

Lets investigate !!!! 


                                                  

To understand the difference, first lets first dig into these methods AddMvc and AddMvcCore , yes we can see the implementation of these methods because Asp.net Core is open source (smile)!!!

AddMvc()








AddMvc() is adding Authorization, the RazorViewEngine and the JsonFormatters we need to get our output going. And most interesting it is also calling the AddMvcCore() method itself, the highlighted part, where as
AddMvcCore() lot shorter and only adding the basic things to get started. But both methods are returning an IMvcCoreBuilder. Interesting is the AddMvcCoreServices(services); method which is adding the ability to return FileContents, RedirectToRouteResults, ActionResolvers, use Controllers, use routing and so on. Really basic functionality.
So when using AddMvcCore() we have to add everything by ourselves. 

Best suited case here can be while building our WebApi, we may not need the usage of RazorViews while building Api's so we can opt for AddMvcCore() in that case .

Lets see the demo


Step 1: Create a asp.net core web application choose the Mvc template.

Step 2 : Go to Startup.cs and do as shown below 

Step 3:  Go to Home controller and do the clean up: 


Step 4: Try executing the url we should be getting Http 404 resource not found .

Step 5: In startup if you change the code to AddMvc() or AddMvcCore().AddRazorViewEngine() as shown below to see the view 

We are adding the Razor view engine to render our View , This component is missing in AddMvcCore().

You can see the demo here .


Comments

Post a Comment

Popular posts from this blog

Part 1 : Asp.Net Core Authentication Using Identity

JSON Patch in Asp.net Core Webapi