The goal is to convert a handful of Attr into DI filter from Autofac using .AsWebApiAuthorizationFilterFor<ApiController>(c => c.GetType()
Feel like I am close but prob just doing it wrong, found a bunch of posts about peram injector but that is not what I am looking to do here.
current failing attempt
builder.RegisterType<SomeFilter>()
.AsWebApiAuthorizationFilterFor<ApiController>(c => c.GetType()
.GetMethods()
.Where(m => m.GetCustomAttributes<SomeAttribute>().Any())
)
.InstancePerRequest();
Goal: add this filter for all api controllers and/or controller methods with a specific attribute
Solution Created From Provided Answers:
- Create custom
IAutofacAuthorizationFilter
and moved the current filter logic in the ATTR to the auth method of that interface. - Added call enable filter for autofac
builder.RegisterWebApiFilterProvider(config);
Registered My Filter
builder.RegisterType<MyFilterFilter>() .AsWebApiAuthorizationFilterFor<BaseTypeApiController>() .InstancePerDependency();
Add check for the original attribute on the controller or the method, if both are null I return.
var controllerAttribute = actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault(); var methodAttribute = actionContext.ActionDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault();
So far that seems to be doing the trick and solved for my requirements.
The second parameter of
AsWebApiAuthorizationFilterFor
is an action selector used to select one method for which the filter is created.To apply conditional registration, you could use
OnlyIf
:You could also build your own
AsWebApiAuthorizationFilterForOnlyIf
extension and do:UPDATE
If you fancy a
scan-and-add-automatically
method, you could use expression tree to dynamically invokeAsWebApiAuthorizationFilterFor
for each controller and method found. There will be quite a bit of code as per you could see below: