views:

467

answers:

3

Hi,

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?

A: 

Please look at the properties of HttpRequest.Url. It is of the type System.Uri.

John Saunders
Thanks for your answer. I have looked at that and I can't determine any functionality for doing this, there is an IsFile property but that is not what I am looking for.
theringostarrs
If I am wrong please point it out!
theringostarrs
Uri.LocalPath will return the path. You should then be able to use the features of System.IO.Path to manipulate that.
John Saunders
So, you had looked at the features of System.Uri before you wrote the question? If so, you should have included that information in your question. In fact, you should edit your question now to add that information.
John Saunders
A: 

Try this:

// get the URI
Uri MyUrl = Request.Url; 
// remove path because System.IO.Path doesn't like forward slashes
string Filename = MyUrl.Segments[MyUrl.Segments.Length-1]; 
// Extract the extension
string Extension = System.IO.Path.GetExtension(Filename);

Note that Extension will always have the leading '.'. e.g. '.css' or '.js'

Keltex
A: 

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.

Damien McGivern