Uri base without backslash

If I create Uri using UriBuilder as follows:

 var rootUrl = new UriBuilder("http", "example.com", 50000).Uri; 

then AbsoluteUri of rootUrl always contains a rootUrl slash like this:

 http://example.com:50000/ 

I would like to create a Uri object without a trailing slash, but that seems impossible.

My workaround is to save it as a string instead and do something ugly:

 var rootUrl = new UriBuilder("http", "example.com", 50000).Uri.ToString().TrimEnd('/'); 

I heard people say that without a slash, Uri is not valid. I do not think this is true. I looked at RFC 3986, and section 3.2.2 says:

If the URI contains an authority component, then the path component must either be empty or begin with a slash ("/").

He does not say that the final slash should be there.

+5
source share
2 answers

An end slash is not required in an arbitrary URI, but it is part of the canonical representation of an absolute URI for requests in HTTP :

Note that the absolute path cannot be empty; if not present in the source URI, it MUST be indicated as "/" (server root).

To adhere to the specification , the Uri class outputs a URI in a form with a trailing slash:

In general, a URI that uses the general syntax for privileges with an empty path should be normalized along the path to "/".

This behavior is not configurable for a Uri object in .NET. Web browsers and many HTTP clients perform the same rewriting when sending requests to URLs with an empty path.

If we want to internally represent our URL as a Uri object rather than a string, we can create an extension method that formats the URL without an end slash, which abstracts this presentation logic in one place, rather than duplicating it every time we need to output the URL display address:

 namespace Example.App.CustomExtensions { public static class UriExtensions { public static string ToRootHttpUriString(this Uri uri) { if (!uri.IsHttp()) { throw new InvalidOperationException(...); } return uri.Scheme + "://" + uri.Authority; } public static string IsHttp(this Uri uri) { return uri.Scheme == "http" || uri.Scheme == "https"; } } } 

Then:

 using Example.App.CustomExtensions; ... var rootUrl = new UriBuilder("http", "example.com", 50000).Uri; Console.WriteLine(rootUrl.ToRootHttpUriString()); // "http://example.com:50000" 
+2
source

You can use the Uri.GetComponents method:

 rootUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) 

To return a string representation of the Uri various components, in this case UriComponents.SchemeAndServer means the components of the circuit, host and port.

You can find out more about this on MSDN:

0
source

Source: https://habr.com/ru/post/1272935/


All Articles