Blankman
Blankman

Reputation: 266960

How to make all static files like css/images/js files not be processed by asp.net mvc?

Is it possible that static files not be processed by the asp.net mvc engine?

Can I do this at the IIS level or something? (without ofcourse creating a seperate IIS website for static files)

Upvotes: 17

Views: 20053

Answers (4)

George Stocker
George Stocker

Reputation: 57872

You need to create an ignore route for the specific types of files you don't want to be served through ASP.NET MVC.

Add the following to your routes, for the types of files you want to ignore.

The following works for files in the root:

routes.IgnoreRoute("{file}.css");
routes.IgnoreRoute("{file}.jpg");
routes.IgnoreRoute("{file}.gif");

If you want to ignore files in a specific directory, you can do this:

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

If you want to combine these into one route, you can (e.g., ignore specific types of files in a directory):

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

This overload of IgnoreRoute accepts a url (the first argument) and a Constraints object of things to ignore.

Since the RouteConstraints in ASP.NET MVC can be implemented multiple ways (including a regex), you can put standard regexes in the second argument.

If you want to implement a custom constraint, there is lots of useful documentation on that subject (say, if your constraint is dynamic at runtime).

Upvotes: 31

Alex from Jitbit
Alex from Jitbit

Reputation: 60566

Be careful, @george-stocker's answer works for static files in the root directory only!!!

To catch static files in all possible directories/subdirectories, use an ignore rule with a "condition", like this:

routes.IgnoreRoute("{*allfiles}", new { allfiles = @".*\.(css|js|gif|jpg|png)" });

Upvotes: 22

Max Toro
Max Toro

Reputation: 28608

Static files are not processed by ASP.NET MVC, unless you have a route that matches the URL of a static file. Maybe you are asking about static files processed by ASP.NET, in that case you should not use runAllManagedModulesForAllRequests="true". Here's a post with more info.

Upvotes: 9

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10512

In Global.asax.cs in the beginning of method RegisterRoutes write the following:

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

replacing Content with the name of a folder containing your static files.

George, however, provided More comprehensive solution

Upvotes: 3

Related Questions