Intercept a file download in C# using either an http module or http handler?

841 views Asked by At

When downloading a file from an ASP.NET / C# web application running on IIS 7.5 server, how do you intercept a pdf file being downloaded within the response? The response has Content-Type of application/pdf and a Content-Length of 10091.

Currently I have written a HttpModule that overrides methods:

public void Init(HttpApplication context){
   context.BeginRequest+=Context_BeginRequest();
   context.EndRequest+=Context_EndRequest();

}

private void Begin_Request(Object sender, EventArgs e){
   // this function does not get called when downloading a file!
}


private void End_Request(Object sender, EventArgs e){
   // this function does not get called when downloading a file!
}

Which function do I need to override in order to intercept file download response?

The web.config looks like:

<system.webServer>
<modules runallManagedModulesForAllRequests="true">

    <add name="MyMod.Module" type="MyMod.Module"/>
</modules>

</system.webServer>
1

There are 1 answers

2
Jason On BEST ANSWER

You don't show how you registered the module in your web.config, but if it looks like this:

<system.webServer>
  <modules>
    <add name="mymodule" type="typename, assemblyname" preCondition="managedHandler" />
  </modules>
</system.webServer>

Then you just need to remove the precondition attribute. Otherwise, your module won't be called for static files (and anything else that might not invoke the managed pipeline).