MVC 4 routing - ignore requests for images

2019-09-10 11:25发布

问题:

I'm trying to prevent users from making requests to access images on their own in my web application, so the user shouldn't be allowed to make this type of request:

sitename/Images/test.jpg

I've tried specifying a route to ignore in RouteConfig.cs but it still serves images on their own, is there a way to prevent this?

This is what I've tried:

routes.IgnoreRoute("{file}.jpg");
routes.IgnoreRoute("Images/{file}.jpg");
routes.IgnoreRoute("{resource}.jpg");
routes.IgnoreRoute("Images/{resource}.jpg");

回答1:

If you want to ignore folder you can write like this:

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

if you want to ignore only certain files in folder you can use this overload of IgnoreRoute() like this:

routes.IgnoreRoute("{Images}", new { assets = @".*\.(jpeg|gif|jpg)(/.)?" });

As you can see constraints parameter can be implemented like RegExp.