从 Host.TopLevelDomain C# 获取有效网站 url

Acquire valid web url from Host.TopLevelDomain C#

给定一个包含部分 url 的字符串,例如 "google.com"

是否可以从该字符串中获取有效的 URI?

预期结果与在任何网络浏览器地址栏中放置 google.com 所获得的结果相同。 前任。 http://www.google.com/

最后我想将这个值传递给一个新的 Uri 对象,这样我就可以在 HttpWebRequest 中使用它来检索网站图标。

您在找这样的东西吗?

class Program
    {
        static void Main(string[] args)
        {

            var URL = "google.com/Somepath/";
            var CorrectedURL = new TopLevelURL(URL,"http").ParsedURL;
            Console.WriteLine(CorrectedURL);
            Console.Read();
        }


    }

    public class TopLevelURL
    {

        private string URL = "";
        private string Protocol = "";
        public string ParsedURL { get; private set; }

        public TopLevelURL(string _URL,string WantedProtocol)
        {
            URL = _URL;
            Protocol = (WantedProtocol == "http" ? "http://" : "https://") ?? "http://";
            ParseURL();
        }

        private void ParseURL()
        {
            if (URL.ToLower().Contains("http"))
            {
                //If the URL is provided with the protocol check the validity of URL
                if (!Uri.IsWellFormedUriString(URL, UriKind.RelativeOrAbsolute))
                    throw new Exception("Malformed URL!");

                //If the URL is provided with the protocol and is valid, just get the absolute URL. e.g: http://helloworld.com
                URL = new Uri(URL).AbsoluteUri.Replace(new Uri(URL).AbsolutePath, "");
            }
            else
            { 
                //If the URL does not have the protocol then start constructing it with the protocol
                URL = Protocol + URL;
                if(!Uri.IsWellFormedUriString(URL,UriKind.RelativeOrAbsolute))
                    throw new Exception("Could not parse the URL. Invalid character before the domain name!");

                URL = new Uri(URL).AbsoluteUri.Replace(new Uri(URL).AbsolutePath,"");

            }
            ParsedURL = URL;
        }



    }

这是简化的。您可以检查 http://doepud.co.uk/blog/anatomy-of-a-url 以制定更严格的规则。上面的示例检查简单协议并在删除路径后吐出 URL。