I'm looking for easy and convenient way to hide action methods in controllers in ASP.NET Core.
For some reason it's hard to find a complete and satisfactory answer.
For example, I want to hide specific action method in a specific controller for a given environment value (i.e. IWebHostEnvironment.EnvironmentName != Development).
I know about ServiceFilterAttribute, but this is the way to prevent execution of a method, and I prefer removing the action method completely from everywhere (as I said, conditionally), including generated swagger schemas. Something like NonAction attribute, but working with a runtime condition.
Still, if possible, I prefer using custom Attribute to decorate an action method.
Does anyone know any convenient ways to implement such behavior?
I think you should be able to do it with creating a custom IApplicationModelConvention
public class RemoveActionConvention : IApplicationModelConvention
{
    public void Apply(ApplicationModel application)
    {
        foreach (var controller in application.Controllers)
        {
            var toBeRemoved = new List<ActionModel>();
            foreach (var action in controller.Actions)
            {
                if (ShouldBeRemoved(action))
                {
                    toBeRemoved.Add(action);
                }
            }
            foreach (var action in toBeRemoved)
            {
                controller.Actions.Remove(action);
            }
        }
    }
}
And add it to MVC conventions
services.AddMvc(options =>
{
    options.Conventions.Add(new RemoveActionConvention());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With