It's not the first time the Uri gives me pain. This time I got a bug reported on one of my libraries where parts of the provided URL got replaced. A URL is defined as a two string parts which are then used to construct a URI. Now, I'm most certainly misusing it, or have been putting to much hope to the smart people behind it. Look at the case below. The desired string is: http://mydomain.com:8081/cloud/test
The problem
var b1 = new Uri("http://mydomain.com:8081/cloud");
var b2 = new Uri("http://mydomain.com:8081/cloud/");
//How many will match http://mydomain.com:8081/cloud/test
Console.WriteLine(new Uri(b1, "/test"));
Console.WriteLine(new Uri(b1, "test"));
Console.WriteLine(new Uri(b2, "/test"));
Console.WriteLine(new Uri(b2, "test"));
gives:
http://mydomain.com:8081/test
http://mydomain.com:8081/test
http://mydomain.com:8081/test
http://mydomain.com:8081/cloud/test
A hacky solution
Before looking at the answer, this was the "hacky" solution I went with:
public static class UriMagic
{
public static Uri Abracadabra(params string[] parts)
=> new Uri(string.Join(
"/",
parts.Select(p => p.Trim(' ', '/'))));
}
Another "fun" finding... the "OriginalString"
Documentation says:
Gets the original URI string that was passed to the Uri constructor.
Try this:
[Fact]
public void Foo()
{
new Uri(new Uri("http://foo.com:80/bar/"), "fun")
.OriginalString
.Should().Be("http://foo.com:80/bar/fun");
}
[Fact]
public void Bar()
{
new Uri(new Uri("http://foo.com:8081/bar/"), "fun")
.OriginalString
.Should().Be("http://foo.com:8081/bar/fun");
}
[Fact]
public void FooBar()
{
new Uri("http://foo.com:8081/bar/fun")
.OriginalString
.Should().Be("http://foo.com:8081/bar/fun");
}
Outcome?
Summary
I'm clearly using it wrong. But for me, it feels to easy to misuse.
//Daniel
header image src: https://pixabay.com/en/doors-choices-choose-open-decision-1767559/