how do you wire up Application_BeginRequest() in asp.net-mvc

leora picture leora · Jul 6, 2011 · Viewed 55.9k times · Source

I see in global.asax.cs from an ASP.NET MVC project

 protected void Application_BeginRequest()
 {
 }

but when I try to add this to my project, I don't see what is calling this method. I see that the base System.Web.HttpApplication has this event but I don't see anything overriding it or subscribing to this event.

Can someone explain how you wire up Application_BeginRequest in ASP.NET MVC?

Answer

Nicholas Piasecki picture Nicholas Piasecki · Nov 18, 2011

I'm afraid Cos's answer isn't quite accurate. You don't have to wire it up because the base HttpApplication class does it for you. There isn't an interface or an override here; HttpApplication uses reflection to hook up these methods to the events based on the method name. So it's a bit of convention-based magic that has been in the framework for a while. It's very strange, and I think they only did it to maintain similarities with Classic ASP back in the day and/or provide a shortcut to avoid writing lots of small HttpModules.

For the curious, load up HttpApplication in Reflector and hunt for the HookupEventHandlersForApplicationAndModules() method. Or, load HttpApplicationFactory and look at the ReflectOnApplicationType() and ReflectOnMethodInfoIfItLooksLikeEventHandler() (love that name!) methods.

Rick Strahl discussed this on his blog a few years ago.

Is it something you really need to know to use ASP.NET? No, but knowing it certainly removes some of the mystery.