Events in HTTPModules
Now we get to add some functionality to our
module.
Imports System
Imports System.Web
Public
Class SampleModule :
Implements
IHttpModule
Public Event
bdet As
bdetEventHandler
Public
Delegate Sub
bdetEventHandler(ByVal
sender As
Object,
ByVal e
As
BrowserEventArgs)
Public
Sub Dispose()
Implements
IHttpModule.Dispose
End
Sub
Public
Sub Init(ByVal
application As
HttpApplication) Implements
IHttpModule.Init
AddHandler application.BeginRequest,
AddressOf
Me.OnBeginRequest
End
Sub
Public
Sub
OnBeginRequest(ByVal
sender As
Object,
ByVal e
As
EventArgs)
Dim app As
HttpApplication = CType(sender,
HttpApplication)
Dim browscap
As HttpBrowserCapabilities
= app.Request.Browser
If browscap.Browser = "Netscape"
Then
RaiseEvent bdet(Me,
New
BrowserEventArgs("Netscape"))
ElseIf browscap.Browser = "IE"
Then
RaiseEvent bdet(Me,
New
BrowserEventArgs("Internet Explorer"))
Else
RaiseEvent
bdet(Me,
New
BrowserEventArgs("another browser"))
End
If
End
Sub
End
Class
<Serializable()>
Public
Class
BrowserEventArgs : Inherits
EventArgs
Private bname
As
String
Public
Property BrowserName()
As
String
Get
Return bname
End
Get
Set(ByVal
Value As
String)
bname = Value
End
Set
End
Property
Public Sub
New(ByVal
BrowserID As
String)
BrowserName = BrowserID
End
Sub
End
Class |
I've added a public event to the code called
bdet and added a delegate for it's custom signature (using the
BrowserEventArgs instead of EventArgs, see the Related Articles
for more information on this) and then raising the event
with the appropriate browser name.
Then in web.config
<httpModule>
<add
name="SampMod"
type="HttpModHan.SampleModule,
HttpModHan"
/>
</httpModule> |
And finally in Global.asax -
Imports HttpModHan
Sub
SampMod_bdet(ByVal
sender As
Object,
ByVal e
As
BrowserEventArgs)
Response.Write("You are using " & e.BrowserName)
End
Sub |
And will look something like -
When running.
Summary
Well, this article should have taught you the
basics of setting up an HTTPModule and adding some events to it to make
it even more useful.