How to deny access to a file with ASP.NET web config but not just locally?

Morteza Hasani picture Morteza Hasani · Mar 3, 2011 · Viewed 12k times · Source

I have a problem with ASP.NET web configuration file. I want to deny some users or roles to accessing a specific PDF file. I am using ASP.NET membership and role management system. So I added this lines of codes to a Web.config file:

<location path="myfile.pdf">
    <system.web>
        <authorization>
            <allow roles="admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

and put it to the directory witch the file is included in it. Now when I run the project in local system I can not access the PDF file wile I login with "admin" role. But when I publish the project on the web server I can not brows the folder but I can view the PDF file when I browse complete path to the PDF file. So:

I can not access: http://www.example.com/folder

but I can view: http://www.example.com/folder/myfile.pdf

Answer

Josh M. picture Josh M. · Mar 7, 2011

IIS is probably serving the PDF file before ASP.Net gets its hands on it. Assuming you're using .Net 4.0, add this to your Web.config file to force all requests to flow through to ASP.Net:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
<system.webServer>