【问题标题】:Getting 'Error binding to target method.' for Delegate.CreateDelegate() in MVC application获取“错误绑定到目标方法。”对于 MVC 应用程序中的 Delegate.CreateDelegate()
【发布时间】:2014-04-09 05:49:30
【问题描述】:

我在 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);

        }
    }

我想将此用作可以在操作上提供的附加检查。问题是它会抛出“Error binding to target method”。我创建了一个控制台应用程序,它能够创建委托。这是网络项目中的问题吗?

我也试过了:

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

已经解决过类似问题herehere

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 c#-4.0 delegates


    【解决方案1】:

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

    当你把它改成:

    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)中工作。

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-11
      • 2021-05-15
      • 2013-06-06
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多