具有依赖注入的IControllerModelConvention

时间:2018-04-26 13:48:46

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

我正在使用asp.net core 2.0 MVC开发一个网站。 我遇到过一种情况,我希望根据某些逻辑将不同的授权过滤器应用于不同的控制器。例如,所有以前缀Identity开头的控制器都会运行一个授权过滤器,而所有其他控制器都会运行另一个授权过滤器。

我跟着this article显示可以通过在IControllerModelConvention方法启动期间向services.addMvc(options)方法添加ConfigureServices方法来完成此操作。

services.AddMvc(options =>
{
    options.Conventions.Add(new MyAuthorizeFiltersControllerConvention());
    options.Filters.Add(typeof(MyOtherFilterThatShouldBeAppliedGlobally));
}

这里是类MyAuthorizeFiltersControllerConvention,你可以看到我正在根据命名约定为每个控制器添加一个特定的授权过滤器。

public class AddAuthorizeFiltersControllerConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        if (controller.ControllerName.StartsWith("Identity"))
        {
            controller.Filters.Add(new AuthorizeFilter(...));

            // This doesn't work because controller.Filters 
            // is an IList<IFilterMetadata> rather than a FilterCollection
            controller.Filters.Add(typeof(AnotherFilter)); 
        }
        else
        {
            controller.Filters.Add(new AuthorizeFilter(...));
        }
    }
}

我遇到的问题是我无法使用typeof(filter)重载以这种方式添加过滤器,就像我在ConfigureServices方法启动时一样。我需要这个,因为我想添加的一些过滤器需要依赖注入才能实例化它们。

我的问题是如何实现这一目标?它甚至可能吗?

1 个答案:

答案 0 :(得分:2)

这是您可以执行的操作:

controller.Filters.Add(new TypeFilterAttribute(typeof(AnotherFilter)));
相关问题