If I create a Uri
using the UriBuilder
like this:
var rootUrl = new UriBuilder("http", "example.com", 50000).Uri;
then the AbsoluteUri
of rootUrl
always contain a trailing slash like this:
http://example.com:50000/
What I would like, is to create a Uri
object without the trailing slash, but it seems impossible.
My workaround is to store it as a string instead, and do something ugly like this:
var rootUrl = new UriBuilder("http", "example.com", 50000).Uri.ToString().TrimEnd('/');
I have heard people say that without the trailing slash, the Uri is invalid. I don't think that is true. I have looked through RFC 3986, and in section 3.2.2 it says:
If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character.
It doesn't say that the trailing slash has to be there.
The trailing slash is not required in an arbitrary URI, but it is the part of the canonical representation of an absolute URI for requests in HTTP:
To adhere to the spec, the
Uri
class outputs a URI in the form with a trailing slash:This behavior is not configurable on a
Uri
object in .NET. Web browsers and many HTTP clients perform the same rewriting when sending requests for URLs with an empty path.If we want to internally represent our URL as a
Uri
object, not a string, we can create an extension method that formats the URL without the trailing slash, which abstracts this presentation logic in one location instead of duplicating it every time we need to output the URL for display:Then:
You can use the
Uri.GetComponents
method:Which would return a
string
representation of theUri
's different components, in this case,UriComponents.SchemeAndServer
means the scheme, host, and port components.You can read more about it on MSDN:
Uri.GetComponents
UriComponents
UriFormat