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:
- Open up the Internet Information Services Manager (Start->Run->InetMgr).
- Right click on the web site you'd like to alter and click properties.
- Click on the Home Directory tab and then click Configuration.
- Find the .aspx extension and click edit. Copy the path the ISAPI .dll and click cancel. (should be something like c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll).
- Click Add, paste in the path to the ASP.NET ISAPI .dll, put .PDF as the extension and choose All Verbs. Click OK.
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"
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.
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\microsoft.net\Framework\v2.0.50727\CONFIG\web.config). Ideally it will save you from writing some code one day.
Hope that made sense.