Autofac ApiController Filters For Methods With Attribute

495 Views Asked by At

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:

  1. Create custom IAutofacAuthorizationFilter and moved the current filter logic in the ATTR to the auth method of that interface.
  2. Added call enable filter for autofac builder.RegisterWebApiFilterProvider(config);
  3. Registered My Filter

        builder.RegisterType<MyFilterFilter>()
            .AsWebApiAuthorizationFilterFor<BaseTypeApiController>()
            .InstancePerDependency();
    
  4. 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.

2

There are 2 best solutions below

4
On

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:

// Conditionally register filter for all controller actions
services.GetContainerBuilder()
    .RegisterType<Filter>()
    .AsWebApiAuthorizationFilterFor<DummyController>()
    .OnlyIf(_ => typeof(DummyController).GetCustomAttributes<SomeAttribute>().Any());

// Conditionally register filter for selected controller action
services.GetContainerBuilder()
    .RegisterType<Filter>()
    // x => x.Get selects Get method defined by DummyController
    .AsWebApiAuthorizationFilterFor<DummyController>(x => x.Get())
    .OnlyIf(_ => 
     typeof(DummyController).GetMethod("Get").GetCustomAttributes<SomeAttribute>().Any());

You could also build your own AsWebApiAuthorizationFilterForOnlyIf extension and do:

if (typeof(DummyController).GetCustomAttributes<SomeAttribute>().Any())
{
    services.GetContainerBuilder()
        .RegisterType<Filter>()
        .AsWebApiAuthorizationFilterFor<DummyController>();
}

UPDATE

If you fancy a scan-and-add-automatically method, you could use expression tree to dynamically invoke AsWebApiAuthorizationFilterFor for each controller and method found. There will be quite a bit of code as per you could see below:

ContainerBuilder containerBuilder = ...
Type[] controllerTypes = ...

// Keep the type registration builder here, and use it for all As actions
var typeRegistrationBuilder = containerBuilder
    .RegisterType<Filter>()
    .InstancePerRequest();

// Scan controllers and methods and build registrations
foreach (Type controllerType in controllerTypes)
{
    // Which means ALL actions in the controller should have the filter registered
    if (controllerType.GetCustomAttributes<SomeAttribute>().Any())
    {
        // Because AsWebApiAuthorizationFilterFor doesn't take non-generic type parameter,
        // so we need to build delegate to invoke AsWebApiAuthorizationFilterFor<controllerType>.

        // Use expression tree.

        // This will build:
        // () => typeRegistrationBuilder.AsWebApiAuthorizationFilterFor<controllerType>()
        Expression.Lambda<Action>(
            Expression.Call(
                typeof(Autofac.Integration.WebApi.RegistrationExtensions),
                "AsWebApiAuthorizationFilterFor",
                new[] { controllerType },
                Expression.Constant(typeRegistrationBuilder))
        ).Compile()(); // Just compile and run this Action

        continue;
    }

    // Controller doesn't have the attribute
    // Scan action methods

    var methods = controllerType.GetMethods()
        .Where(mi => mi.GetCustomAttributes<SomeAttribute>().Any());
    foreach (MethodInfo method in methods)
    {
        // Now the method has the attribute
        // Again, use expression tree to build method call, but this time, with a selector

        // First, build method call expression parameters for each parameter on the method
        // Just need to pass default(T) in, because Autofac literally just need the method
        IEnumerable<Expression> parameters = method.GetParameters()
            .Select(p => p.ParameterType)
            .Select(Expression.Default);

        // Build method selector
        // This will build:
        // _ => _.SomeMethod(parameters)

        ParameterExpression controller = Expression.Parameter(controllerType, "_");
        LambdaExpression methodSelector = Expression.Lambda(
            typeof(Action<>).MakeGenericType(controllerType),
            Expression.Call(controller, method, parameters),
            controller);

        // This will build:
        // () => typeRegistrationBuilder.AsWebApiAuthorizationFilterFor<controllerType>(
        //     _ => _.SomeMethod(parameters));
        Expression.Lambda<Action>(
            Expression.Call(
                typeof(Autofac.Integration.WebApi.RegistrationExtensions),
                "AsWebApiAuthorizationFilterFor",
                new[] { controllerType },
                Expression.Constant(typeRegistrationBuilder),
                methodSelector)
        ).Compile()(); // Just compile and run this Action
    }
}
0
On

Solution Created From Provided Answers:

  1. Create custom IAutofacAuthorizationFilter and moved the current filter logic in the ATTR to the auth method of that interface.
  2. Added call enable filter for autofac builder.RegisterWebApiFilterProvider(config);
  3. Registered My Filter

        builder.RegisterType<MyFilterFilter>()
            .AsWebApiAuthorizationFilterFor<BaseTypeApiController>()
            .InstancePerDependency();
    
  4. Add check for the original attribute on the controller or the method, if both are null I return. Added check to filter method: OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)

        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.

Note: you can use the same method to apply the filter to all controller methods and then check for the attribute. for my use case I had a base class for the controllers I needed to impact. to register for all change the filter registration to .AsWebApiAuthorizationFilterFor<ApiController>()