The question is clear from the title itself. Let us put the environment details to get more clarity.
Problem
It is an ASP.Net Core 2.1 Web API application that runs on .Net Framework 4.8. It has its own controller classes in its assembly. In addition to that, there are some controller classes in other projects that need to be added via the nuget package manager. Assuming they are not conflicting.
This was not supported out of the box prior to ASP.Net Core 2.1 where we have to inherit our web API controller classes from the base APIController class. We had to do something with the ControllerBuilder class or inherit the IAssemblyResolver class. Something complex.
Solution
With ASP.Net Core 2.1, there is no need to complicate things as long as we are inheriting the controller class from the ControllerBase class and decorate it with [ApiController].
We have to make sure the other assembly that contains the controller classes is available in /bin folder of the hosting application. If not in the /bin folder it's reachable to be loaded into the application.
Sample
It's not complete by just telling it is simple. A working solution can be downloaded from GitHub. It has a readme.md file to get started.
Points to note
APIController v/s ControllerBase
Now there may be a question arising. What is the difference between these APIController v/s ControllerBase classes for ASP.Net WebAPI? Tune for a dedicated blog post on it. Wait it's something that happened years back. Why should there be one more blog post? The answer is right there in StackOverflow. Below are the main points.
- ASP.Net WebAPI and ASP.Net MVC merged in ASP.Net Core.
- ASP.Net Core provides a new base class called ControllerBase for developing WebAPIs. Use that where ever possible as that is the future. Even .Net 5 is providing ControllerBase as the way to develop WebAPIs.
- If we are stuck with APIController class, ASP.Net Core is providing a shim named WebAPICompactShim. Use that ONLY during the migration time.
- Once again, do not depend more on WebAPICompactShim as there was an announcement that it will be removed in the future, and it is removed in ASP.Net Core 3.x as a breaking change.
- If we need to develop the MVC Controllers that support views, inherit from the Controller class that has views support.
No comments:
Post a Comment