1

我试图枚举修饰方法的参数以检索应用于这些参数的自定义属性以确定特定值。

我的拦截器中有以下内容,它显示了我尝试使用的两种不同方法,都检索和枚举 GetParameters,但一种使用 IsDefined,另一种使用 GetCustomAttributes:

public void Intercept(IInvocation invocation)
{
    try
    {

        var parameters = invocation.Request.Method.GetParameters();
        for (int index = 0; index < parameters.Length; index++)
        {
            foreach (var attrs in parameters[index]
                .GetCustomAttributes(typeof(EmulatedUserAttribute), true))
            {

            }

        }

        foreach (var param in invocation.Request.Method.GetParameters())
        {
            if (param.IsDefined(typeof (EmulatedUserAttribute), false))
            {
                invocation.Request.Arguments[param.Position] = 12345;
            }

        }


        invocation.Proceed();
    }
    catch(Exception ex)
    {
        throw;
    }
}

我要找的属性很简单,没有实现:

public class EmulatedUserAttribute : Attribute { }

和拦截属性:

[AttributeUsage(AttributeTargets.Method)]
public class EmulateAttribute : InterceptAttribute
{
    public override IInterceptor CreateInterceptor(IProxyRequest request)
    {
        return request.Context.Kernel.Get<IEmulateUserInterceptor>();
    }
}

而我拦截的方法:

[Emulate]
public virtual List<UserAssociation> GetAssociatedProviders([EmulatedUser] int userId)
{
    return _assocProvAccountRepo.GetAssociatedProviders(userId);
}

如您所见,我用 EmulatedUser 属性修饰了 userId,并用我的拦截器属性修饰了方法。除了我看不到 userId 上的属性外,其他一切都很好。

有什么想法为什么我在该方法上看不到自定义属性?我猜这与方法不是实际的“调用目标”有关,但我看不出有什么办法可以解决这个问题。请帮忙!

4

1 回答 1

1

布兰登,

试试这个代码。我让它工作得很好。这是我定义类的方式:

public class Interceptor : SimpleInterceptor
{
    protected override void BeforeInvoke(IInvocation invocation)
    {
        var invokedMethod = invocation.Request.Method;
        if (invokedMethod.IsDefined(typeof(EmulateAttribute), true))
        {
            var methodParameters = invokedMethod.GetParameters();
            for (int i = 0; i < methodParameters.Length; i++)
            {
                var param = methodParameters[i];
                if (param.IsDefined(typeof (EmulatedUserAttribute), true))
                {
                    invocation.Request.Arguments[i] = 5678;
                }
            }
        }
    }
}

public interface IIntercepted
{
    [Emulate]
    void InterceptedMethod([EmulatedUser] int userId);
}

public class Intercepted : IIntercepted
{
    [Emulate]
    public void InterceptedMethod([EmulatedUser] int userId)
    {
        Console.WriteLine("UserID: {0}", userId);
    }
}

我正在请求一个实例IIntercepted而不是Intercepted。如果我请求具体类,拦截将不起作用。也许这可以让你走上正确的道路。

var kernel = new StandardKernel();
kernel.Bind<IIntercepted>().To<Intercepted>().Intercept().With<Interceptor>();

var target = kernel.Get<IIntercepted>();

target.InterceptedMethod(1234); // Outputs 5678
于 2014-03-18T15:40:56.010 回答