简体   繁体   English

使用Uri的相对路径

[英]Relative path using Uri

Uri test = new Uri(new Uri("http://www.google.com/test"), "foo"); Uri test = new Uri(new Uri(“http://www.google.com/test”),“foo”);

returns http://www.google.com/foo 返回http://www.google.com/foo

but Uri test = new Uri(new Uri("http://www.google.com/test/"), "foo"); 但是Uri测试=新的Uri(新的Uri(“http://www.google.com/test/”),“foo”);

returns http://www.google.com/foo/test 返回http://www.google.com/foo/test

It seems the last slash is very important, is there a unified way to return http://www.google.com/foo/test in all cases 似乎最后一个斜线非常重要,是否有统一的方法可以在所有情况下返回http://www.google.com/foo/test

Well, you need to ensure that your base URI ends with a / character: 那么,您需要确保您的基URI以/字符结尾:

public Uri CombineUris(string baseUri, string relativeUri)
{
    if (!baseUri.EndsWith("/")) {
        baseUri += "/";
    }
    return new Uri(new Uri(baseUri), relativeUri);
}

Make sure to pass the root URI with the trailing / . 确保使用尾随/传递根URI。 Last slash is very important. 最后的斜线是非常重要的。 Consider http://www.example.com/foo/bar.html, bar2.html . 考虑http://www.example.com/foo/bar.html, bar2.html It should be resolved to http://www.example.com/foo/bar2.html . 它应该解析为http://www.example.com/foo/bar2.html

Uri test = new Uri(new Uri(GetSafeURIString("http://www.google.com/test")), "foo");



private static string GetSafeURIString(uri)
{
   if(uri == null)
       return uri;
   else
       return uri.EndsWith("/") ? uri : uri + "/";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM