Wednesday, October 15, 2008

Stop ASP.NET From Serving Specific File Types

No Service Please

The great thing about Web Servers is that they will serve pretty much anything on disk. This can get interesting if there's content that you need your application to be able to get at but don't want to served off. Sure you could mess with file permissions or these files in the App_Data directory (which doesn't serve any content). But if this problem happens to plague you in v1.1 or you're in v2.0 and don't want to refactor any code then there's another option. You can simply tell your web application to no longer serve files of a certain type. What's even better is you don't have to write a single line of code.

Stopping ASP.NET From Serving File Types

The following example will stop PDFs from being served by ASP.NET.

The first step is to have ASP.NET handle requests for .PDFs, we do this with the following steps:

  1. Open up the Internet Information Services Manager (Start->Run->InetMgr).
  2. Right click on the web site you'd like to alter and click properties.
  3. Click on the Home Directory tab and then click Configuration.
  4. Find the .aspx extension and click edit. Copy the path the ISAPI .dll and click cancel. (should be something like c:\windows\\framework\v2.0.50727\aspnet_isapi.dll).
  5. Click Add, paste in the path to the ASP.NET ISAPI .dll, put .PDF as the extension and choose All Verbs. Click OK.Adding .PDF mapping to ASP.NET ISAPI .DLL.

IIS will now have ASP.NET handle all requests for .PDF files in this web site. We now use the ASP.NET System.Web.HttpForbiddenHandler to stop the serving of these files. Open up the web.config for your web application and insert the following code in the <httpHandlers> section.

<add verb="*" path="*.pdf"
type="System.Web.HttpForbiddenHandler" />

That's it! Now whenever someone tries to get at a .PDF for this web application an HttpException will be thrown with an error message of "This type of page is not served." You can now go about catching that error with custom error handler and displaying a less user hostile message (should you wish). Either way these file types are now protected.

2008.10.15 13.15.30

Other Uses

This is actually how ASP.NET protects file types from being served (.cs, .csproj, .resx). You can see these HttpForbiddenHandler mappings in the root web.config (C:\WINDOWS\\Framework\v2.0.50727\CONFIG\web.config). Ideally it will save you from writing some code one day.

Hope that made sense.


No comments: