asp.net-coreasp.net-apicontroller

Which class would inherit a Controller in a project ASP.NET Core Web API?


I am following a tutorial to build Web API Application, but I do not understand from which class a controller has to inherit.

In my tutorial is explained to inherit from ControllerBase, but around the web I saw that Controller who inherit from ApiController.

What is the best path to follow?


Solution

  • "I am following a tutorial to build Web API Application, but I do not understand from which class a controller has to inherit?"

    First of All you didn't shared which document you are following, on the other than it depends which kind of asp.net or asp.net core project controller you have taken. For example if you have taken asp.net core controller it should be inherited from ControllerBase if you have taken asp.net MVC it should be inherited from Controller but if you have taken only asp.net web API controller it should be inherited from ApiController as you may know Web API controllers inherited from ApiController

    So here is the details what you are confused on:

    Asp.net Web API2 Controller Inherited From ApiController:

    It has been developed on asp.net framework 4.8 before .Net core.

    enter image description here

    Asp.net Core MVC Controller Inherited From Controller:

    Developed on asp.net core MVC

    enter image description here

    Asp.net Core Controller Inherited From ControllerBase:

    All asp.net core no matter MVC or Web API Inherited from ControllerBase. After release version of asp.net core 2.1, you wouldn't get anything Inherited ApiController all from ControllerBase and curently on .Net 5.0 or .Net 6.0

    enter image description here

    "In my tutorial is explained to inherit from ControllerBase, but around the web I saw that Controller who inherit from ApiController?"

    It depends on which version of asp.net orasp.net core project you are working on. If you are using asp.net core 5.0 or latter than it should use ControllerBase by default as convension.

    Note: If you would like to know more details on diffrent kind of ASP.NET MVC and Web API with controllers or even ASP.NET Core you can check here our official document

    Hope it would guided you accordingly.