防止ASP.NET Core在单独的程序集中发现控制器 [英] Prevent ASP.NET Core discovering Controller in separate assembly

查看:44
本文介绍了防止ASP.NET Core在单独的程序集中发现控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Core API,它引用了一个包含 Controller 的nuget包.

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

默认情况下,此控制器已注册并且可以响应请求.但是,我只想在某些情况下添加此内容-例如如果在DEV环境中.

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.

我的启动看起来像这样:

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

我希望在调用 AddCointrollers 注册此控制器后需要调用 AddApplicationPart(typeof(ClassInPackage).Assembly)吗?

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?

推荐答案

好,我找到了一个解决方案-删除包含 Controller ApplicationPart .程序集中的任何其他依赖项仍然可以使用.

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

在Startup.cs中/无论您在何处进行IoC:

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);
   }
}

您还可以通过扩展方法来操作 ApplicationParts :

You can also manipulate ApplicationParts via the extension method:

AddMvc().ConfigureApplicationPartManager()

这不适合我,因为我已经在nuget包中编写了扩展方法

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

https://docs.microsoft.com/zh-CN/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-5.0

这篇关于防止ASP.NET Core在单独的程序集中发现控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆