asp.net mvc - 在 MVC 应用程序中获取 Delegate.CreateDelegate() 的'Error binding to target method.'



我在 MVC3 应用程序中有一个自定义操作过滤器

public class CustomActionFilter:ActionFilterAttribute
    {
        public Func<IDictionary<string, object>, bool> AdditionalCheck { get; set; }
        public CustomActionFilter()
        {
        }
        public CustomActionFilter(Type declaringType, string methodName)
        {
            MethodInfo method = declaringType.GetMethod(methodName);
            AdditionalCheck = (Func<IDictionary<string, object>, bool>)Delegate.CreateDelegate(typeof(Func<IDictionary<string, object>, bool>), method);
        }
    }

我想将其用作可以在操作中提供的附加检查。问题是它会抛出"错误绑定到目标方法"。我创建了一个控制台应用程序,它能够创建委托。这是 Web 项目中的问题吗?

我也试过:

AdditionalCheck = (Func<IDictionary<string, object>, bool>)Func<IDictionary<string, object>, bool>.CreateDelegate(typeof(Func<IDictionary<string, object>, bool>), method);

已经在这里经历了类似的问题

我不知道它是否解决了您的问题,但是您提供的代码不会以这种方式工作,因为您没有目标(声明类型)的实例,您要在其中调用您的方法。

当您将其更改为:

public class CustomActionFilter : ActionFilterAttribute
{
    private object _target;
    public Func<IDictionary<string, object>, bool> AdditionalCheck { get; set; }
    public CustomActionFilter()
    {
    }
    public CustomActionFilter(Type declaringType, string methodName)
    {
        MethodInfo method = declaringType.GetMethod(methodName);
        _target = Activator.CreateInstance(declaringType);
        AdditionalCheck = (Func<IDictionary<string, object>, bool>)Delegate.CreateDelegate(typeof(Func<IDictionary<string, object>, bool>),_target, method);
    }
}

然后它在我的测试项目 (MVC 3) 中工作。

但我建议重新考虑你的代码结构,也许你可以找到另一种方法,而不使用反射。

希望这有帮助。

最新更新