36

Suppose that both FirstModule and SecondModule handle the Application_BeginRequest event. Will it execute in the order defined in the web.config?

<httpModules>
  <add type="MyApp.FirstModule, MyApp" name="FirstModule"/>
  <add type="MyApp.SecondModule, MyApp" name="SecondModule"/>
  <add type="OtherApp.OtherModule, OtherApp" name="OtherModule"/>
</httpModules>

Are there other ways that the order can be specified?

jessegavin
  • 74,067
  • 28
  • 136
  • 164

2 Answers2

38

According to this forum post, HttpModules are executed in the order in which they were registered. This makes sense to me, because otherwise the <clear> and <remove> directives would also not work as expected, e.g. when used like this:

<httpModules> 
   <clear/>
   <add... />
</httpModules>
M4N
  • 94,805
  • 45
  • 217
  • 260
  • 2
    Someone in the forum post DOES say that. However there were several people who also said that you shouldn't depend on it. – jessegavin Mar 11 '10 at 19:04
  • 10
    Shouldn't depend on it yes, not because it doesn't work but because of design considerations and promoting loose coupling between the modules. But there are no cases where the ordering of modules will be different to what is in the config file. Hope this helps. – Phil Bennett Mar 22 '10 at 08:40
  • It appears you can order them, however the ordering appears to be locked, and you must unlock the entries to affect the actual ordering. – jamiebarrow Aug 17 '11 at 14:53
  • @jamiebarrow I would be interested to read more about this. Do you have a url or some sort of resource where you found out about the locking/unlocking. – jessegavin Feb 14 '12 at 20:28
  • 1
    check this as well before investing time in this answer. http://stackoverflow.com/a/14974151/398715 – Samuel Jan 08 '14 at 09:38
  • Can MS be so lame to not include an explicit ordering mechanism? – thepirat000 Jul 22 '19 at 21:25
4

According to the Internet Information Services (IIS) 7.0 Resource Kit book extract from Microsoft Press,

To resolve such relative ordering dependencies, the administrator can control the relative ordering of modules by changing the order in which they are listed in the modules section.

This works because the server uses the order in the modules configuration section to order module execution within each request processing stage. By placing module A before module B in the list, you can allow module A to execute before module B.

Community
  • 1
  • 1
bkqc
  • 831
  • 6
  • 25