Caution: Asp.NET MVC Filters can be invoked in reverse order

In one of my current Asp.NET MVC web applications I use a number of custom filters to perform processes such as logging, compression, whitespace removal and so on. Some of these are designed only to be ran after actions or results have executed. In order words, they only override the “OnActionExecuted” or “OnResultExeuted” methods.

These filters also have explicit ordering. For example, I intended to remove whitespace first, and then compress, so for example I would have 2 filters explicitly ordered like this:

[WhitespaceFilter(Order=1)]

[CompressionFilter(Order=2)]

However, what I found out is that when executing, the order gets reversed. After digging into the source code of the Asp.NET MVC Framework, I realized that this is by design. Basically the OnActionExecuting and OnResultExecuting events were being fired in order, but the “ed” events were being reversed, which makes sense when you think about it. What this means is that you have to be careful to remember this when defining the order of filters which only respond to the “ing” events!

Advertisement

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.