Prevent ASP.NET Core discovering Controller in separate assembly

旧时模样 提交于 2021-02-19 08:15:30

问题


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?


回答1:


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://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-5.0



来源:https://stackoverflow.com/questions/64789567/prevent-asp-net-core-discovering-controller-in-separate-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!