Limiting HttpModule to only process certain requests

We use directory browsing on a specific section of our website, but our users don't really like the default ASP.NET

directory browsing. To be honest, we don't particularly care for it either.

I came across mvolo's custom directory browsing module and I attempted to use it. However, I discovered that if I have it enabled in my root web.config, it allows directory browsing on all folders without a default page (as you would expect). If I set enabled="false" in the root, it throws an HttpException, which is being caught by my generic error page, but every request is causing the exception, like when the page requested has additional images to request during the load.

As I believe (and I could be wrong), the default directory browsing module only checks for the enabled attribute if there is no default folder and you aren't requesting a specific file (for example, mysite.com/images/ versus mysite.com/images/logo.gif).

I have reconstructed the functionality of the custom module, but I am unable to figure out how to limit the module to only fully execute in situations where directory browsing would be necessary if enabled -- and not for every single request. Here is a chunk of code from the module:

    public void Init(HttpApplication app)
    {
        app.PreRequestHandlerExecute += new EventHandler(this.OnPreRequestHandlerExecute);
    }

    public void OnPreRequestHandlerExecute(object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        config = (DirectoryListingConfigSection)WebConfigurationManager.GetSection("directoryBrowsing", context.Request.Path);

        if (this.config == null)
        {
            throw new Exception("Missing <directoryBrowsing> configuration section.");
        }

        /* I only want to check this if it's necessary, not for things 
           like mysite.com/images/logo.gif or mysite.com/about/history.aspx 
           -- those shouldn't give a 403 error */
        if (!config.Enabled)
        {
            context.Response.Status = "403 Forbidden";
        }

        /* The rest of the code goes below, and should only process 
           if Directory Browsing is necessary and enabled */
    }

Modules are executed on every request that goes through the ASP.Net, there is no way to restrict calls to module based on type of request.

You need to built checks into your module's code to only handle requests that are of interest of that module.

Depending on the stage you should have access to most of information about request. During PreRequestHandlerExecute you have all possible information about incoming request, including Url, headers and related session state if present.

链接地址: http://www.djcxy.com/p/43798.html

上一篇: ASP.NET HttpModule请求处理

下一篇: 限制HttpModule只处理某些请求