Appending multiple segments with System.Uri

2019-06-16 04:07发布

问题:

var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1");
var uri2 = new Uri(uri1, "2");   

Unexpectedly, uri2 is http://localhost/2. How would I append to uri1 so it's http://localhost/1/2 intead? Does Uri do this, or do I need to fallback to strings? Incidentally, I've tried adding leading/trailing slashes almost everywhere.

回答1:

"1" and "2" are "file name portion" of a url. If you make "1" to look more like directory path it will work ok "1/":

var baseUri = new Uri("http://localhost/");
var uri1 = new Uri(baseUri, "1/");
var uri2 = new Uri(uri1, "2"); 

Note: "file name portion" is not a real term, as Url only have "path" and "query" component, but normally last chunk of a path is treated as file name: "/foo/bar/file.txt".

When you combine 2 path you want to replace some tail portion of the first path with the second one. In your case it ends up to have just "file name" segment for both :"/1" and "2" (if you put real value like "/myFile.txt" and "NewFile.txt" in combining it would be easier to see why it behaves this way).



标签: c# uri