Path.Combine for URLs?

前端 未结 30 2441
不思量自难忘°
不思量自难忘° 2020-11-22 14:28

Path.Combine is handy, but is there a similar function in the .NET framework for URLs?

I\'m looking for syntax like this:

Url.Combine(\"http://MyUrl.         


        
30条回答
  •  误落风尘
    2020-11-22 15:13

    Combining multiple parts of a URL could be a little bit tricky. You can use the two-parameter constructor Uri(baseUri, relativeUri), or you can use the Uri.TryCreate() utility function.

    In either case, you might end up returning an incorrect result because these methods keep on truncating the relative parts off of the first parameter baseUri, i.e. from something like http://google.com/some/thing to http://google.com.

    To be able to combine multiple parts into a final URL, you can copy the two functions below:

        public static string Combine(params string[] parts)
        {
            if (parts == null || parts.Length == 0) return string.Empty;
    
            var urlBuilder = new StringBuilder();
            foreach (var part in parts)
            {
                var tempUrl = tryCreateRelativeOrAbsolute(part);
                urlBuilder.Append(tempUrl);
            }
            return VirtualPathUtility.RemoveTrailingSlash(urlBuilder.ToString());
        }
    
        private static string tryCreateRelativeOrAbsolute(string s)
        {
            System.Uri uri;
            System.Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri);
            string tempUrl = VirtualPathUtility.AppendTrailingSlash(uri.ToString());
            return tempUrl;
        }
    

    Full code with unit tests to demonstrate usage can be found at https://uricombine.codeplex.com/SourceControl/latest#UriCombine/Uri.cs

    I have unit tests to cover the three most common cases:

    Enter image description here

提交回复
热议问题