tags:

views:

377

answers:

4

I'm observing some really confusing behavior with the Application_BeginRequest event in my Global.asax file (in an ASP.NET MVC app). When running through the debugger, if I Refresh my browser (IE7), this event fires twice. If I click a link or otherwise manually request a page, it fires once - as expected.

Why does a refresh cause BeginRequest to fire twice?

I'm observing this with a brand new MVC project with the following addeded to Global.asax.cs

protected void Application_BeginRequest() { 
    //executed twice
}

For context, I'm trying to add a new object to the HttpContext.Current.Items collection during this event, so it will persist through the entire request process. Obviously, I don't want this to happen twice for a single refreshed request!

A: 

I'm not sure why this is occuring but I find it's easier to create a BaseController class and have all my controllers inherit from it. Alter the constructor to add your item to the HttpContext.

Spencer Ruport
Good idea. This occurred to me, and appears that it will have to be my solution now.
Kurt Schindler
A: 

Do you have a reference in your HTML to something that also passes the ASP.NET pipeline, like a dynamically generated image or something like that?

Philippe Leybaert
A: 

Something that surprised me a while back was that if you have an img tag in your html that doesn't have a proper image path, some browsers will make a request to the original page. Here is a related blog post.

Chris Shaffer
+2  A: 

Are you sure it's really 2 request to the same URL? I would think that the second is probably some dynamic JS, CSS or image file. Try to find out either with Fiddler or by looking at HttpContext.Current.Request.Uri in the debugger

chris166
Bingo! I didn't realize that this will fire for other content files. It seems the strangness with a refresh vs other requests is due to IE requesting all content (the url, css, js, etc) on a refresh, whereas click on a link or re-entering the url it was caching everything but the actual url request...
Kurt Schindler