1

目标是使用 Autofac 将少量 Attr 转换为 DI 过滤器.AsWebApiAuthorizationFilterFor<ApiController>(c => c.GetType()

感觉我很亲密,但很可能只是做错了,发现了一堆关于 peram 注射器的帖子,但这不是我想要在这里做的。

当前失败的尝试

       builder.RegisterType<SomeFilter>()
            .AsWebApiAuthorizationFilterFor<ApiController>(c => c.GetType()
                .GetMethods()
                .Where(m => m.GetCustomAttributes<SomeAttribute>().Any())
            )
            .InstancePerRequest();

目标:为所有 api 控制器和/或具有特定属性的控制器方法添加此过滤器

根据提供的答案创建的解决方案:

  1. 创建自定义IAutofacAuthorizationFilter并将 ATTR 中的当前过滤器逻辑移动到该接口的 auth 方法。
  2. 为 autofac 添加了呼叫启用过滤器builder.RegisterWebApiFilterProvider(config);
  3. 注册我的过滤器

        builder.RegisterType<MyFilterFilter>()
            .AsWebApiAuthorizationFilterFor<BaseTypeApiController>()
            .InstancePerDependency();
    
  4. 在控制器或方法上添加对原始属性的检查,如果两者都是 null 我返回。

        var controllerAttribute = actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault();
        var methodAttribute = actionContext.ActionDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault();
    

到目前为止,这似乎可以解决问题并满足我的要求。

4

2 回答 2

2

的第二个参数AsWebApiAuthorizationFilterFor是一个操作选择器,用于选择为其创建过滤器的一种方法。

要申请有条件注册,您可以使用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());

您还可以构建自己的AsWebApiAuthorizationFilterForOnlyIf扩展并执行以下操作:

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

更新

如果您喜欢一个scan-and-add-automatically方法,您可以使用表达式树为找到的每个控制器和方法动态调用AsWebApiAuthorizationFilterFor。如下所示,将会有相当多的代码:

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
    }
}
于 2020-04-02T02:04:55.707 回答
0

根据提供的答案创建的解决方案:

  1. 创建自定义IAutofacAuthorizationFilter并将 ATTR 中的当前过滤器逻辑移动到该接口的 auth 方法。
  2. 为 autofac 添加了呼叫启用过滤器builder.RegisterWebApiFilterProvider(config);
  3. 注册我的过滤器

        builder.RegisterType<MyFilterFilter>()
            .AsWebApiAuthorizationFilterFor<BaseTypeApiController>()
            .InstancePerDependency();
    
  4. 在控制器或方法上添加对原始属性的检查,如果两者都是 null 我返回。添加检查过滤方法:OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)

        var controllerAttribute = actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault();
        var methodAttribute = actionContext.ActionDescriptor.GetCustomAttributes<AttributeReplacedByFilterAttribute>().FirstOrDefault();
    

到目前为止,这似乎可以解决问题并满足我的要求。

注意:您可以使用相同的方法将过滤器应用于所有控制器方法,然后检查属性。对于我的用例,我有一个需要影响的控制器的基类。注册所有更改过滤器注册为.AsWebApiAuthorizationFilterFor<ApiController>()

于 2020-04-03T00:06:57.763 回答