9

I tried to assign the PreSendRequestHeaders Event in the global.asax file in the "Application_Start" method. But this does not work.

private void Application_Start()
{
    PreSendRequestHeaders += OnPreSendRequestHeaders;           
}

private void OnPreSendRequestHeaders(object sender, EventArgs e)
{
   // this is not called
}

The OnPreSendRequestHeaders is not called, why? Is it possible to assign the PreSendRequestHeaders method in the global.asax?

Chris
  • 4,325
  • 11
  • 51
  • 70

1 Answers1

11

Just use:

protected void Application_PreSendRequestHeaders(Object source, EventArgs e)
{

}

Or instantiate the handler:

protected void Application_Start()
{
    PreSendRequestHeaders += new EventHandler(OnPreSendRequestHeaders);
}

protected void OnPreSendRequestHeaders(object sender, EventArgs e)
{
    // should work now
}
pklosinski
  • 219
  • 3
  • 9
  • Have you tried that? When I do that my OnPreSendRequestHeaders method is never called. What have you done to get this to work? – Chris Jul 11 '12 at 18:53
  • 4
    The first one works perfectly for me, but the second one does not (just as @Chris' initial question says) – Arve Systad Feb 13 '13 at 08:15
  • 1
    **Never** hook up event handlers in Application_Start. ASP.NET creates multiple instances of your Global class so that multiple HTTP requests can be handled simultaneously, but Application_Start is called for only one of those instances. This means that your event handlers would only be in effect for one of the Global instances, not all of them. – Michael Liu Feb 24 '20 at 23:15