使用相对URI

时间:2010-07-12 13:23:42

标签: .net uri relative-path

我对相对URI有点麻烦

我有一个简单的HttpListener应用程序正在侦听给定的前缀(目前它是http://+:80/Temporary_Listen_Addresses/,但它可以是任何其他有效的前缀)。

对于任何给定的请求,我正在尝试计算所请求的URI相对于该前缀的内容,例如,如果有人请求http://localhost/Temporary_Listen_Addresses/test.html,我想获得test.html

最好的方法是什么?

更新:MakeRelativeUri方法对我不起作用,因为它不知道等效地址。例如,使用“localhost”时,以下工作正常:

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

但是,如果您浏览http://127.0.0.1/http://machinename/等,它就无效...

3 个答案:

答案 0 :(得分:2)

您可以在URI类上使用MakeRelative方法。

编辑:如果URL的计算机名称或权限部分出现问题,您可以执行的操作是每次创建具有相同权限的新URL,并仅使用现有URI中的路径。例如,您可以通过执行以下操作来创建输入URI:

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);

答案 1 :(得分:1)

这是一个非常愚蠢的方法来完成这项工作:

    var relativeUri = context.Request.Url.AbsolutePath.
                      Substring(baseUri.AbsolutePath.Length);

答案 2 :(得分:0)

您可以从URL获取最后一次出现的'/'的索引,并获取紧随其后的子字符串。