How to check current request resource is a page in

2019-04-05 07:37发布

问题:

I have an IHttpModule implementation with a delegated method hooked to PostAcquireRequestState, for each HTTP Request, I would like to know how to check if the current requested resource is a Page (aspx) discriminating all other resources like *.css, *.ico, *.png and so on.

Actually I can do the following:

private static void OnPostAcquireRequestState(object sender, EventArgs e)
{
  bool isPage = HttpContext.Current.Request.Path.EndsWith(".aspx");
}

But I would like to know if there is something different to do than hard checking with ".aspx".

回答1:

One thing you could do is to get a list of registered HTTP Handlers and check whether they are handled by a system class. Assuming you don't name your own classes in a namespace System.*, this is quite foolproof:

using System.Configuration;
using System.Web.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
HttpHandlersSection handlers = (HttpHandlersSection) config
                               .GetSection("system.web/httpHandlers");

List<string> forbiddenList = new List<string>();

// next part untested:
foreach(HttpHandlerAction handler in handlers.Handlers)
{
    if(handler.Type.StartsWith("System."))
    {
        forbiddenList.Add(handler.Path);
    }
}

Alternatively, you can revert the lookup and list all existing handlers except those in your own (or current) domain, possibly provided some exceptions (i.e., if you want to override an existing image handler). But whatever you choose, this gives you full access to what's already registered.


Note: it's generally easier to do the reverse. You now seem to want to blacklist a couple of paths, but instead, if you can do whitelisting (i.e., make a list of those extensions that you do want to handle) you can make it yourself a lot easier.