c# - asp .net core 中的自动 Controller 检测

标签 c# asp.net-core .net-core

Asp .net core MVC在启动时自动检测项目中的 Controller 。我一直在寻找一种方法来防止某些 Controller 发生这种情况。结果,我发现我可以实现 IControllerFactory 来动态过滤 Controller 。但是,据我了解,它是用于 Controller 创建,而不是检测。有没有其他方法可以在不实现 IControllerFactoryIControllerActivator 的情况下做到这一点?启动时是否有其他组件参与 Controller 检测?

IControllerActivatorIControllerFactory 用于 Controller 创建。

最佳答案

您需要实现自己的 IControllerActivator 并将逻辑添加到其中。

我建议向 Controller 添加一个属性,并在 Create 方法中使用反射来启用/禁用 Controller

public class CustomControllerResolver : IControllerActivator
{
    public object Create(ControllerContext actionContext)
    {
        var actionDescriptor = actionContext.ActionDescriptor;
        var controllerType = actionDescriptor.ControllerTypeInfo.AsType();
        return actionContext.HttpContext.RequestServices.GetRequiredService(controllerType);
    }

    public virtual void Release(ControllerContext context, object controller)
    {
    }
}

在 ServicesCollection 中注册您的自定义解析器

services.Replace(ServiceDescriptor.Transient<IControllerActivator, CustomControllerResolver>());

关于c# - asp .net core 中的自动 Controller 检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56714360/

相关文章:

mono - Kestrel 命令抛出无法加载 libuv。确保 libuv 已安装并可用作 libuv.so.1

c# - 从 API 身份验证返回的 Azure Blob SAS Url 失败 .net core

docker - 如何使用ASP.Net Core从Docker容器连接到DB2?

c# - 无法通过启用的 UseAuthentication 访问 HomeController 路由

c# - 无法将类型 'Newtonsoft.Json.Linq.JObject' 转换为复杂类型

c# - 有没有办法使用 Quaternion.FromToRotation 来支持使用一个轴?

asp.net - 无法在 Visual Studio 2017 中创建 "Asp.Net Core Web application"

c# - Blazor 获取 div 位置/坐标

c# - 如何对 Entity Framework 进行单元测试?

c# - 寻找 C# 代码来处理 .PAR2 文件