开发者

Relative path using Uri

开发者 https://www.devze.com 2023-01-25 11:09 出处:网络
Uri test = new Uri(new Uri(\"http://www.google.com/test\"), \"foo\"); returns http://www.google.com/foo

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

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

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

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

It seems the la开发者_Go百科st slash is very important, is there a unified way to return http://www.google.com/foo/test in all cases


Well, you need to ensure that your base URI ends with a / character:

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 /. Last slash is very important. Consider http://www.example.com/foo/bar.html, bar2.html. It should be resolved to 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 + "/";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消