Search code examples
c#filerequesthttpmodule

HttpModule/HttpApplication testing whether url is a request for a file


Within a HttpModule I would like to check whether the url ends with a file:

ie. www.example.com/images/images.css

and what the file extension is ie. css or js

In the Begin_Request event handler, using the Url property of the Request object nested in the HttpApplication, I am currently cutting of the file extension using String operations. Is there a better way to do this?


Solution

  • The code below should get you the extension for the requested file.

    private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
    
        string ext = System.IO.Path.GetExtension(context.Request.Path);
        // ext will always start with dot
    
    }
    

    But unlike file types such as .aspx and .ashx file types such as .js and .css that you have used in your example are not by default registered with the ASP.Net dll within IIS so when they are requested IIS doesn't pass the request through the ASP.Net pipeline so no HttpModules or HttpHandlers will run. How you configure this to happen depends on what version of IIS you are running on.