2

I put a sub directory in my ASP MVC 4 application called "Protected" and I dropped a simple test.html file in that directory, but I cannot for the life of me figure out how to get my custom, global AuthorizeAttribute class to trigger when I view the test.html file in my browser.

I'm using IIS Express in Integrated mode, so I thought this would work. I even tried IIS 7 in Integrated mode, but it still won't work for me.

But maybe I'm going about things all wrong. Maybe it's some misunderstanding I have.

Basically, I need to programatically authorize requests to static files within that folder. Is there another way to do that?

Update as of 4/9/2013 10:07:25 AM by AD: Zidad's answer below got things going in the right direction, but I'm having trouble getting the route configured now. Here's what I've got, but the file is still being served up directly instead of hitting the Home/File action.

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute("NotFound", "protected/test.html", new { controller = "Home", action = "File" });

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

Update as of 4/9/2013 10:20:54 AM by AD: Ohhhhhhhhhhhhhhhhhhh, now I get it! Definitely a misunderstanding on my part. Guess I still have a few things to learn. :)

JackPoint
  • 4,031
  • 1
  • 30
  • 42
Alex Dresko
  • 5,179
  • 3
  • 37
  • 57

1 Answers1

3

First make sure to add to your web.config to make sure IIS doesn't bypass .NET when serving static files:

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

then you should be able to add a web.config file to your protected folder containing:

<authorization>
  <deny users="?" />
</authorization>

If you do want to use the 'AuthorizeAttribute', you could map a route to a controller action returning the files in your protected folder, and apply the attribute to that method, like this:

Can an ASP.NET MVC controller return an Image?

UPDATE: to keep the URL's to your protected files the same you could configure the route like this:

routes.MapRoute(
                name: "ProtectedFile", 
                url: "protected/{name}", 
                defaults: new { controller = "Home", action = "File", name = "index.html" });

Then write your action like this:

public ActionResult File(string name){
// return file
}

Behold: There's a performance penalty for serving all static files through .NET, and this action doesn't consider all the HTTP best practices that IIS would do automatically for you when serving static files, like static content compression, returning "not modified (304)" HTTP status, adding ETAGs, etc.

Community
  • 1
  • 1
Wiebe Tijsma
  • 10,173
  • 5
  • 52
  • 68