Search code examples
c#asp.netasp.net-coreasp.net-web-apiasp.net-apicontroller

Is there a way in a child controller to hide actions from a base generic controller?


There is a Controller that has 7 actions that are reused by all other child controllers. It is possible to hide endpoints, if it is necessary, using "path order" in the attribute. The following code hides the parent action:

[Post("{id}, Order = 1")]//In the parent

[Post("{id}")]//In the child.

However, that only works if the child and parent have the same route. If they have a different route but you need to hide in the child controller 1 of the 7 parent controller actions for whatever reason, how do you do it?


Solution

  • If you are finding yourself having to "hide" routes in your children controllers, Id recommend taking a moment to re-asses how you have organized the parent object.

    Lets say for your seven routes, A, B, C... G, you have three controllers that all needed to "hide" the G route.

    You instead might want to breakup your BaseController into two layers.

    BaseController which has routes A through F, and then a SecondaryBaseController which inherits from BaseController and implements route G, which all but those three controllers inherit from. The remaining three just inherit from BaseController

    Then those three controllers wont have a G route at all that needs hiding.

    If you have your hiding of routes all over the place and many of the routes are hidden in some controllers, not hidden in others, that's an indication that you don't need the BaseController at all, and should be trimming down to just the endpoints that you never find require hiding.

    Summarized: If you find yourself having to hide endpoints you exposed via inheritance, its a code smell that you could do with trimming the parent class up or refactoring how you built the layers above.