C# Uri Trailing Slash

Jamie Nordmeyer
Jun 10 · 2 min read

Many libraries that deal with pathing (taking path “fragments” and appending them together to form a larger path) do not care whether you add trailing separator characters or not. If you supply them, they let the fragment be. If not, then the fragment separator is automatically added. For instance, both Node’s path library, as well as.NET’s System.IO.Path methods, allow you to provide file path fragments, and if there are missing path separators between, they will be added automatically.

Apparently, this is the the case for Uri’s in .NET. Looking through the documentation, there is no direct equivalent for concatenating Uri path fragments. The way that you have to do so is with the Uri constructor. I ran into this issue last week at work, and it cost me a several hours of lost time as I troubleshot the issue. Take a look at this code snippet, which I ran in LinqPad:

baseUri1 has no trailing slash in the Uri, whereas baseUri2 does. If the Uri class worked like other pathing classes, I’d expect both Console.WriteLine calls to produce http://www.somesite.com/api/person/100/hobbies/13. However, that is NOT the case. Instead, I get the following:

http://www.somesite.com/api/person/100/13 http://www.somesite.com/api/person/100/hobbies/13

Notice that hobbies is completely missing from the first Uri. It didn’t just append 13 to hobbies… it actually removed hobbies from the Uri altogether before appending the 13. What…?!? I assumed that the Uri class would add the missing trailing slash, so when my code was not working after deployment to our development environment, it wasn’t immediately clear why it couldn’t reach the REST API that it was relying on. Only after adding in additional logging was I able to figure out that the URI being used to talk to our API was invalid.

I do my absolute best to not make assumptions, especially when using the .NET BCL classes and methods. However, it looks like we can still be bit from time to time when something works one way, while we expected that it worked another…


Originally published at JamieNordmeyer.net.

    Jamie Nordmeyer

    Written by

    I’m a Full-stack Software Engineer and Architect living and working in the Portland, OR Metro area, specializing in .NET and web technologies.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade