开发者

Relative path using Uri

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜