Using RouteExistingFiles to block access to existing files even if no route exists

In ASP.net MVC 2, I can use routes.RouteExistingFiles = true; to send all requests through the routing system, even if they exist on the file system.

Usually, this ends up hitting the "{controller}/{action}/{id}" route and throws an exception as the controller cannot be found.

I do not want to use that route though (I have only a few URLs and they are specifically mapped), yet I would still like to prevent access to the file system.

Basically I want to Whitelist pages using IgnoreRoute. Is there a built-in way to do this?

My current approach is to still have a route "{*anything}" and generate a 404 when this is hit, but I’m just wondering if something is built-in already?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is one of the few valid uses of Web.config authorization in an ASP.NET MVC application. 🙂

I’d recommend setting RouteExistingFiles back to false (so that Routing and the MVC pipeline don’t handle these requests, IIS and ASP.NET core do). Put all of the files for which you want to deny access into a single folder, then drop a Web.config into that folder:

<configuration>
  <system.web>
    <authorization>
      <deny users="*"/>
    </authorization>
  </system.web>
</configuration>

This will prevent IIS and ASP.NET from serving these files directly.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x