Configure IIS for passing static-file requests to ASP.Net/MVC
At my company we had several ASP.Net MVC projects what needed to serve some files with a custom MVC Controller/Action. The general problem with this is that IIS tries hard to serve simple files like PDF’s, pictures etc. with its static-file handler which is generally fine but not for files or lets say file-content served by our own action.
The goal is to switch off the static-file handling of IIS for some paths. One of the current projects came up with the following requirements so I did some research and how we can do this better then we did in past projects.
Requirements:
- Switch it off only for /Data/…
- Switch it off for ALL file-types as we don’t yet know what files the authors will store in somewhere else.
This means that the default static-file handling of IIS must be switched off by some “magic” IIS config. In other apps we switched it off on a per file-type basis for the entire application. I finally came up with the following IIS-config (in web.config). It sets up a local configuration for the “data”-location only. Then I used a simple “*” wild-card as the path (yes, this is possible) to transfer requests to the ASP.Net. It looks like this:
<location path="data"> <system.webServer> <handlers> <add name="nostaticfile" path="*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> </location>
Tested with IIS 7.5.
Alternative:
Instead a controller one could also use a custom HttpHandler for serving such special URL’s/Resources. In this project I decided using an action for this because of the central custom security which I needed for the /Data/… requests as well and got for free when using Action instead a HttpHandler.
Categories