Base Uri without a trailing slash

前端 未结 2 1843
走了就别回头了
走了就别回头了 2021-01-17 19:19

If I create a Uri using the UriBuilder like this:

var rootUrl = new UriBuilder(\"http\", \"example.com\", 50000).Uri;
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 20:08

    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:

    Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).

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

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

    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:

    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 bool 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"
    

提交回复
热议问题