简体   繁体   中英

How to exclude Webresource.axd from firing my custom HttpModules

I've been searching around all day on the web but found nothing. In my web.config I set:

<modules runAllManagedModulesForAllRequests="false">

And

<add name="MyModule" type="namespace.to.MyModule" preCondition="managedHandler" />

And this is preventing MyModule (hooked to PostAuthenticateRequest in this example) from being fired on static resources like images, css, js and so on. But the module is still fired by .axd files inside the page, in particular it's fired from WebResource.axd

I added this check in my HttpModule and it works:

            ' Skip the module for non aspx requests like .axd or url without default document
     Private Sub Application_PostAuthenticateRequest(ByVal source As Object, ByVal e As EventArgs)
        Dim request = DirectCast(source, HttpApplication).Request
        If request.CurrentExecutionFilePathExtension.ToLower <> ".aspx" Then
            Exit Sub
        End If

This is hooked to PostAuthenticateRequest. If you hook to other events, like for example OnEndRequest, beware you have access to HttpContext and not HttpApplication so add this instead:

  Protected Overridable Sub OnEndRequest(context As HttpContext)          
  ' Skip the module for non aspx requests like .axd or url without default document
        Dim request = context.Request
        If request.CurrentExecutionFilePathExtension.ToLower <> ".aspx" Then
            Exit Sub
        End If

Also note that when calling an URL without document, like for example http://www.yoursite.com IIS triggers a request to http://www.yoursite.com/Default.aspx (or whatever def document you set). So even if your page is empty you will trigger 2 requests. IIS Site states that "For default document requests, the first request is to an extensionless URL. Therefore, IIS does not run any managed modules that are marked with a precondition of managed Handler during initial request processing." But that's not true. Even with my HttpModule marked with attribute precondition="managedHandler" with a request like http://www.yoursite.com/ it still gets triggered two times (one for / and one for /Default.asp). Anyway with the workaround posted here above you solve this as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM