Working with relative URIs
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 t开发者_运维技巧hat 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...
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);
Here is a really stupid way to get this done that works:
var relativeUri = context.Request.Url.AbsolutePath.
Substring(baseUri.AbsolutePath.Length);
You can get from the URL the index of the last occurrence of '/' and get the substring, that begins right after it.
精彩评论