Ran into an interesting issue today. We have an application that I am building. One of the pieces of this is application is the ability to download file, but, since security is always important, the file isn’t where the URL says it is. Using ASP.Net routing, I can say it is in one place, when it is really somewhere else and then just output the binary data as a response. Except for that pesky file extension. If the URL doesn’t have a file extension, everything is fine. If the URL has a file extension, the StaticFile Handler takes over and gives me a 404. After far too much Googling for a work around and finding lots of almost functionality answers, I came up with this.

First, determine the path that will never have files. We can use /documents for example.  What I am saying is, the URL http://www.example.com/documents/ will never actually have any files. In fact, in my solution, the documents directory doesn’t even exist.

Now, in your web.config, add the following:

[xml] <location path="documents">
<remove name="StaticFile"/>
<add name="WildCardRequestHandler" verb="GET" path="*" type="System.Web.Handlers.TransferRequestHandler"/>

Now, your routes will work as expected even when there is an extension but only for that path. In other words, going to http://www.example.com/documents/test.txt will allow your handler to handle it instead of having a 404 for a file you already knew didn’t exist.