使用运行时生成的处理程序挂钩到HttpApplication.BeginRequest会导致NullReference异常

时间:2014-03-16 22:56:27

标签: c# asp.net events handler expression-trees

连接到事件HttpApplication.BeginRequest(以及其他一些HttpApplication事件)与运行时生成的委托之后

var expr = Expression.Lambda<EventHandler>(Expression.Empty(),
    new[]
    {
        Expression.Parameter(typeof (object)),
        Expression.Parameter(typeof (EventArgs))
    });
var handler = expr.Compile();
application.BeginRequest += handler;

我收到错误:

NullReferenceException: Object reference not set to an instance of an object.]
 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +120
  System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +114

环境:ASP.NET 4。

如果在其他委托调用中调用此委托,则异常消失: application.BeginRequest += (s, e) =>{handler(s, e);};

这种方法并不能让我满意。

这种行为似乎特定于HttpApplication,因为其他类以预期的方式运行。 请问有人可以解决这个问题。

1 个答案:

答案 0 :(得分:1)

发现,这是因为访问了MemberInfo.ReflectedType.ToString()。在动态方法中,MemberInfo.ReflectedType为Null。如果使用TypeBuilder在生成的类型中创建方法,则设置ReflectionType。