代码之家  ›  专栏  ›  技术社区  ›  Justin

使用相对URI

  •  2
  • Justin  · 技术社区  · 16 年前

    我在相对uri方面有点麻烦

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

    http://localhost/Temporary_Listen_Addresses/test.html test.html .

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

    但是如果你浏览到 http://127.0.0.1/ http://machinename/ 等。。。

    3 回复  |  直到 16 年前
        1
  •  2
  •   NG.    16 年前

    你可以用 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);
    
        2
  •  1
  •   Digital Mindspring    15 年前

        var relativeUri = context.Request.Url.AbsolutePath.
                          Substring(baseUri.AbsolutePath.Length);
    
        3
  •  0
  •   vlood    16 年前

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

    推荐文章