6

I've got an ASP.NET Core API that references a nuget package that contains a Controller.

By default, this controller is registered and can respond to requests. However, I only want to add this in certain circumstances - e.g. if it's in the DEV environment.

My Startup looks like this:

services.AddControllers()
.AddMvcOptions(cfg => {
   cfg.Filters.Add(new CustomExceptionFilterAttribute())
});

I expected I'd need to call AddApplicationPart(typeof(ClassInPackage).Assembly) after calling AddCointrollers to register this controller?

Can someone advise a way I can enable / disable the registration of this controller?

David McEleney
  • 3,397
  • 1
  • 26
  • 32
  • Does this answer your question? [Conditionally disable ASP.NET MVC Controller](https://stackoverflow.com/questions/11604773/conditionally-disable-asp-net-mvc-controller) – David Edel Nov 11 '20 at 15:46
  • @DavidEdel it would prevent the execution of the action methods, but the endpoints would still be visible on swagger etc, so ideally we could hide it there too.. – David McEleney Nov 11 '20 at 16:08
  • If conditional directive like this #if DEBUG ..... #endif can help you? You can use attribute routes with it too. – Serge Nov 11 '20 at 17:06

1 Answers1

3

Ok, I've found a solution - remove the ApplicationPart that contains the Controller. Any other dependencies in the assembly can still be used.

In Startup.cs / wherever you do your IoC:

if(hideControllerFromOtherAssembly)
{
   var appPartManager = (ApplicationPartManager)services.FirstOrDefault(a => a.ServiceType == typeof(ApplicationPartManager)).ImplementationInstance;
   var mockingPart = appPartManager.ApplicationParts.FirstOrDefault(a => a.Name == "MyMockLibrary.Namespace");

   if(mockingPart != null)
   {
      appPartManager.ApplicationParts.Remove(mockingPart);
   }
}

You can also manipulate ApplicationParts via the extension method:

AddMvc().ConfigureApplicationPartManager()

This wasn't suitable for me as I'd written an extension method in my nuget package

https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-5.0

David McEleney
  • 3,397
  • 1
  • 26
  • 32
  • 1
    Just a side-note. Just imaging someone has authored many controllers that are high customizable. You are a user of library of such controllers. You are picky and does not want to have all controllers. Do you really want to remove all controller by hand AS CUSTOMER????? – Teneko Mar 21 '21 at 07:25