由于签名或安全透明性,Create Delegate会引发绑定错误

时间:2013-12-17 20:02:37

标签: c# asp.net-web-api delegates .net-4.5 code-access-security

我正在使用C#4.0和.NET 4.5。

我有这个类,它是当前语境中的入口点:

public static class HttpConfigurationImporter
        {
            public static readonly string ConfigurationMethodName = "Register";
            public static readonly string ConfigClassName = "WebApiConfig";
            public static readonly string HelpPageConfigClassName = "HelpPageConfig";

            public static HttpConfiguration ImportConfiguration(string assemblyPath)
            {
                var assembly = Assembly.LoadFrom(assemblyPath);

                string originalDirectory = Environment.CurrentDirectory;
                Environment.CurrentDirectory = Path.GetDirectoryName(assemblyPath);

                Type webApiConfigType = assembly
                                  .GetTypes()
                                  .FirstOrDefault(t => t.Name == ConfigClassName);

                MethodInfo registerConfigMethod = webApiConfigType
                    .GetMethod(ConfigurationMethodName
                    , BindingFlags.Static | BindingFlags.Public);

                  //ERROR on this LINE
                  Action<HttpConfiguration> registerConfig = Delegate.
                    CreateDelegate(typeof(Action<HttpConfiguration>), 
                    registerConfigMethod)
                    as Action<HttpConfiguration>;

                HttpConfiguration config = new HttpConfiguration();
                registerConfig(config);
                ImportHelpPageConfiguration(assembly, config);
                Environment.CurrentDirectory = originalDirectory;
                return config;
            }
     }

当我尝试在另一个程序集中为此后续目标创建委托时..:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration configuration)
        {
            configuration.MapHttpAttributeRoutes();
        }
    }

我收到错误:Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

删除此部分:

//ERROR on this LINE
Action<HttpConfiguration> registerConfig = Delegate.
                    CreateDelegate(typeof(Action<HttpConfiguration>), 
                    registerConfigMethod)
                    as Action<HttpConfiguration>;

–并尝试以这种方式调用Register方法

registerConfigMethod.Invoke(new object(), new object[] { config });

–代替

registerConfig(config);

它将返回更准确的错误,例如我的情况:

  

System.ArgumentException:'类型为'System.Web.Http.HttpConfiguration'的对象不能转换为类型'System.Web.Http.HttpConfiguration'。'

对于构建的程序集和执行此代码的程序集,我有不同的版本system.web.http.dll