asp.net-core-mvc

Remove single controller from `ConfigureApplicationPartManager` in ASP.NET Core


I'm aware that _mvcBuilder.ConfigureApplicationPartManager allows me to remove complete assemblies from the AppParts (remove all controllers of one assembly). But is there a possibility to remove only a single controller?

I'd like to be able to control what ASP.NET Core MVC controllers of my library are available via settings.


Solution

  • You can selectively remove individual controllers in ASP.NET Core by customizing the IApplicationFeatureProvider:

    public class CustomControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature>
    {
        private readonly HashSet<Type> _excludedControllers;
    
        public CustomControllerFeatureProvider(IEnumerable<Type> excludedControllers)
        {
            _excludedControllers = new HashSet<Type>(excludedControllers);
        }
    
        public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
        {
            // Remove controllers that match the types in _excludedControllers
            feature.Controllers
                .Where(controller => _excludedControllers.Contains(controller.AsType()))
                .ToList()
                .ForEach(controller => feature.Controllers.Remove(controller));
        }
    }
    

    In Program.cs, configure the ApplicationPartManager to use your custom feature provider:

    var builder = WebApplication.CreateBuilder(args);
    
    // Assume we have a setting that tells us which controllers to exclude
    var excludedControllers = new List<Type>
    {
                typeof(YourNamespace.Controllers.YourController) // Specify the controller type to exclude
            };
    
    builder.Services.AddControllersWithViews().ConfigureApplicationPartManager(partManager =>
    {
        partManager.FeatureProviders.Add(new CustomControllerFeatureProvider(excludedControllers));
    });