我有一个这样的过滤器:
public class CustomFilterattribute : ActionFilterattribute,IAuthorizationFilter { public MyPropery Property { get; set; } .... }
我需要为我的项目中的每个动作运行
我试图在GlobalFilters注册,但是我的属性没有被注入
我试过This solution注册我的过滤器,但没有被调用
有什么想法呢?
解决方法
有一种在AutoFac中注册MVC全局过滤器的新方式。首先,从您的RegisterGlobalFilter中删除过滤器注册,因为我们将Autofac句柄添加到我们的控制器/动作而不是MVC。
然后,注册您的容器如下:
var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType<MyProperty>().As<IProperty>(); builder.Register(c => new CustomFilterattribute(c.Resolve<IProperty>())) .AsActionFilterFor<Controller>().InstancePerHttpRequest(); builder.RegisterFilterProvider(); IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
请注意,通过将Controller类传递到扩展AsActionFilterFor()中,我们告诉AutoFac将此过滤器应用于从Controller类派生的所有类(在MVC中是所有控制器)。由于我们调用AsActionFilterFor()没有任何参数,我们也指定我们希望将过滤器应用于指定控制器中的所有操作。如果要将筛选器应用于选择控制器和操作,可以使用如下所示的lambda表达式:
builder.Register(c => new CustomFilterattribute(c.Resolve<IProperty>())) .AsActionFilterFor<HomeController>(c => c.Index()) .InstancePerHttpRequest();
如果您的操作需要参数,请使用default关键字来指定:
builder.Register(c => new CustomFilterattribute(c.Resolve<IProperty>())) .AsActionFilterFor<HomeController>(c => c.Detail(default(int))) .InstancePerRequest();
请注意,您必须根据您注册的过滤器使用不同的扩展方法,以下是支持的过滤器类型:
> AsActionFilterFor> AsAuthorizationFilterFor> AsExceptionFilterFor> AsResultFilterFor
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。