user1751825
user1751825

Reputation: 4309

Global.asax - Application_BeginRequest vs Handles Me.BeginRequest

There seem to be 2 different ways to execute code in Global.asax.vb on BeginRequest, and I'm not sure where I should use one over the other.

I can define a sub like so...

Sub Application_BeginRequest(sender As Object, e As EventArgs)

or define an event handler like so...

Private Sub Global_asax_BeginRequest(sender As Object, e As EventArgs) Handles Me.BeginRequest

I've been using these methods interchangeably in various sites, but now I'm curious as to whether one is more correct than the other, or if there are different situations where each might be preferable.

If I define both, I've noticed that both run, but the event handler runs first.

Upvotes: 2

Views: 7096

Answers (1)

pfx
pfx

Reputation: 23254

Both represent event handler methods that serve the same purpose, with the difference that Application_BeginRequest has been automatically set up by ASP.NET and the other one Global_asax_BeginRequest has been registered explicitly in your code.

See MSDN:

ASP.NET automatically binds application events to event-handler methods in the Global.asax file using a naming convention of Application_event, such as Application_BeginRequest and Application_Error.

Actually Application_BeginRequest is a shortcut for Sub Application_BeginRequest(sender As Object, e As EventArgs) Handles Me.BeginRequest.

Your custom event handler Global_asax_BeginRequest runs first because at compile time the event subscription made via the Handles keyword ends up in the constructor of the Global_asax class, giving it the chance to register to this event first, before Application_BeginRequest can be hooked. When the BeginRequest event gets raised, the order of registration matters and gets respected.

This becomes clear if you decompile the build assembly with eg. ILSply to C# as shown in the image below. Notice the autogenerated event subscription in the constructor.

enter image description here

If you want your custom event handler to run after Application_BeginRequest, you have to make a manual subscription in the Init method via AddHandler.

The code below shows the different event subscriptions for BeginRequest and the order of execution.

Public Class Global_asax
    Inherits HttpApplication

    Public Overrides Sub Init()
        AddHandler Me.BeginRequest, AddressOf handleBeginRequest
    End Sub

    Sub Application_BeginRequest(sender As Object, e As EventArgs)
        'Runs second.
    End Sub

    Private Sub Global_asax_BeginRequest(sender As Object, e As EventArgs) Handles Me.BeginRequest
        'Runs first.
    End Sub

    Private Sub handleBeginRequest(sender As Object, e As EventArgs)
        'Runs third.
    End Sub
End Class

Upvotes: 5

Related Questions