views:

81

answers:

2

I'm having a little trouble with relative URIs

I have a simple HttpListener app that is listening in on a given prefix (currently it is http://+:80/Temporary_Listen_Addresses/, but it could be any other valid prefix).

For a any given request, I'm trying to work out what the requested URI is relative to that prefix, so for example if someone requested http://localhost/Temporary_Listen_Addresses/test.html, I want to get test.html.

What's the best way to do this?

Update: The MakeRelativeUri method didn't work for me as it doesn't know about equivalent addresses. For example, the following worked fine when using "localhost":

Uri baseUri = new Uri("http://localhost/Temporary_Listen_Addresses/");
Uri relative  = baseUri.MakeRelativeUri(uri);

However it doesn't work if you browse to http://127.0.0.1/ , or http://machinename/ etc...

+1  A: 

You can use the MakeRelative method on the URI class.

EDIT: What you can do if the machine name or authority part of the URL is a problem is create a new URL with the same authority each time and only use the path from the existing URIs. For instance, you can create your input URI by doing something like:

UriBuilder b = new UriBuilder();
b.Path = input.Path; //this is just the path portion of the input URL.  
b.scheme = "http";
b.host = "localhost"; // fix the host so machine name isn't an issue

input = b.Uri;
URI relative = baseUri.MakeRelative(input);
SB
This doesn't quite work as expected - I'll elaborate in my question.
Kragen
A: 

You can get from the URL the index of the last occurrence of '/' and get the substring, that begins right after it.

vlood