MikeWyatt
MikeWyatt

Reputation: 7871

Blocking static content in MVC 3

What's the best way to prevent users from downloading specific files in my Content directory?

Should I add a Web.config to /Content, like I already have in /Views?

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <httpHandlers>
      <add path="SecretFolder/*" verb="*" type="System.Web.HttpNotFoundHandler" />
      <add path="SecretFile.pdf" verb="*" type="System.Web.HttpNotFoundHandler" />
    </httpHandlers>
  </system.web>

</configuration>

Or should I create a custom routing rule?

Or is there an even better way?

Upvotes: 0

Views: 372

Answers (2)

Adam Tuliper
Adam Tuliper

Reputation: 30152

Basically exactly as you have above - AS LONG as you don't have another route that would get to this via a controller. Judging from the file types and structure this doesn't seem to be the case (a concern is that you have two routes going to the same file - and using the authorization elements in a web.config is recommended against in MVC specifically for this reason)

You want to use exactly what is already used by MVC. See the integration of "HttpNotFoundHandler" into your web.config at (I know.. you already have it) : http://completedevelopment.blogspot.com/2011/06/using-views-outside-of-views-or-other.html

This is how content inside of your /Views folder is already blocked - so this is already 'mvc-ish'

Upvotes: 1

Jerad Rose
Jerad Rose

Reputation: 15513

This is exactly what the <authorization> element is for in web.config. This will give you granular control over what users can see which files. You can provide as little or much control as you need.

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

However, this assumes that you are implementing ASP.NET authorization using IPrincipal, which I would recommend if you need this sort of control over your content.

Upvotes: 1

Related Questions