【发布时间】:2019-01-10 18:01:52
【问题描述】:
我正在使用 asp.net core 2.0 MVC 开发一个网站。
我遇到过一种情况,我想根据某些逻辑将不同的授权过滤器应用于不同的控制器。例如,所有以前缀 Identity 开头的控制器都将运行一个授权过滤器,而所有其他控制器将运行另一个授权过滤器。
我关注this article,表明这可以通过在ConfigureServices 方法的启动过程中向services.addMvc(options) 方法添加IControllerModelConvention 实现来完成,如下所示。
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(...));
}
}
}
我遇到的问题是我无法像在启动时使用ConfigureServices 方法那样使用typeof(filter) 重载来添加过滤器。我需要这个,因为我想添加的一些过滤器需要依赖注入来实例化它们。
我的问题是如何实现这一目标?有没有可能?
【问题讨论】:
-
您是否尝试将过滤器添加到 DI 容器?
-
@Brad 我已将过滤器添加到 DI 容器中。这不是这里的问题。问题在于可以将过滤器添加到控制器的方法。
Filters属性只接受过滤器的实例,而不接受Type。
标签: c# asp.net-core asp.net-core-mvc