Wednesday, April 7, 2010

Disallowing access to files in an ASP.NET website with HttpForbiddenHandler

Disallowing access to files in ASP.NET is a very easy task to accomplish.

In this example, I will disallow access to the file called private.txt that is situated at the root of the website.

When I access this file normally, I get the following:


To disallow access to the file, use the Error Generator Handler HttpForbiddenHandler. This generates a 403 Forbidden error when the user tries to access that file.

To use the handler, simply add it to your <httpHandlers> section in the web.config:

<httpHandlers>
    <add verb="*" path="private.txt" type="System.Web.HttpForbiddenHandler"/>
</httpHandlers>

This is what the user will not get when he tries to access the file:




The HttpForbiddenHandler can also be used to disallow access to multiple or even folders.

In the following example, I will be disallowing access to all the files that have the .private extension:

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