Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeginRequest fires for static files in ASP.NET MVC app

I was under the impression that static files (CSS, images, @font-face files, etc) bypassed ASP.NET completely, and were served directly by IIS.

However, my BeginRequest event handler is being called for every HTTP request, including those for static files. This concerns me because I'm creating an Entity Framework data context to be used for the lifetime of each request in that event handler. I don't want to create those contexts if they're never going to be used.

I'm using IIS 7 on Windows 7 Ultimate with no special handler mappings defined. Do I have it wrong? Should these events be firing?

like image 216
Brian Sullivan Avatar asked Oct 29 '10 17:10

Brian Sullivan


3 Answers

I believe a default ASP.NET MVC site has this set in the web.config.

<modules runAllManagedModulesForAllRequests="true" />  

This means every .NET module will be loaded for every IIS request. This is required for ASP.NET MVC to handle extension-less routing. It's essentially a wildcard mapping that you would write in IIS that would match everything and route it to ASP.NET that lives in the web.config.

Read more here, including a way to disable the behavior if you aren't using .NET 4.0. It is nasty, but it's the cleanest solution for sites that can't deal with the overhead of having static files served by asp.net.

like image 96
Jab Avatar answered Nov 16 '22 16:11

Jab


BeginRequest will be triggered for all requests (including static content) if:

  • You're using Visual Studio's development web server.
  • You've configured IIS to do so.

Please take a look at: http://forums.asp.net/t/1220664.aspx

like image 20
rsenna Avatar answered Nov 16 '22 15:11

rsenna


In addition to fixing the issue for your static files, you could use Lazy initialization Lazy<T> for your ObjectContext: http://msdn.microsoft.com/en-us/library/dd997286.aspx

like image 1
Ian Mercer Avatar answered Nov 16 '22 15:11

Ian Mercer