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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
You can try to use middleware to check if the route is allowed.Here is a demo:
//add the urls which you want to hidden to string[] urls
string[] urls = { "Child1/Action1", "Child2/Action2" };
app.Use(async (context, next) =>
{
var s = context.Request.Path.ToString();
if (urls.Any(s.Contains)) {
//if path contains any one in urls,return 404 not found
context.Response.StatusCode = 404;
return;
}
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
});
Method 3
There is the NonAction attribute, which you can put in the overridden method like that:
[NonAction]
public override Task<IActionResult> GetAll() => base.GetAll();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
