danielwertheim

danielwertheim


notes from a passionate developer

Developer that lives by the mantra "code is meant to be shared".

Share


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

Uri wonders...or not

Daniel WertheimDaniel Wertheim

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/

Developer that lives by the mantra "code is meant to be shared".

Comments