Search code examples
c#asp.net-mvcasp.net-mvc-3profilingstatic-resource

ASP.NET MVC - what is the earliest point in the request cycle where you can detect a static resource request?


To give the question some context, I've written a profiler which is called on Application_BeginRequest but it's logging everything (ie javascripts, images etc). While it would be possible as a last resort to add filtering to the profiler client, I'd much rather only activate the profiler when it can be determined that the request requires routing. Ideally it would be in Application_BeginRequest but I don't think it would be possible without redundant processing of the incoming request for routing...

So in short, when is the earliest point in the request life cycle that I can determine if a request is for a static resource or not, and how would you go about it?

Is it perhaps possible to derive from or hook into System.Web.Routing.RouteTable and call my profiler code from there?


Solution

  • I've tried approaching it from a different angle and am much happier with the result. Basically - why detect static resource requests when you can just not 'route' them at all? In global.asax:

    private readonly string[] STATIC_CONTENT_PATHS = new string[] { "css", "js", "img" }; 
    
    public static void RegisterRoutes(RouteCollection routes)
    {    
        foreach (string path in STATIC_CONTENT_PATHS) { routes.IgnoreRoute(path + @"/{*foo}"); }
    
        // other MapRoute calls here
    }
    

    Now I no longer need to check for static requests, although if I do want to for whatever reason I can still do the following:

    protected void Application_BeginRequest()
    {            
        if (IsStaticRequest())
        {
             // do something here
        }
    }
    
    private bool IsStaticRequest()
    {
       var result = Request.Url.AbsolutePath.Split('/');
       if (result.Length < 2) return false;
       return STATIC_CONTENT_PATHS.Contains(result[1]);
    }
    

    Since I know with absolute certainly what the only paths I'll be serving static content from are, this seems like a fairly robust solution. I'm still open to other ideas but I think this suits my needs well.