从主机获取有效的web url.TopLevelDomain c#
本文关键字:url TopLevelDomain web 主机 获取 有效 | 更新日期: 2023-09-27 18:16:52
给定一个包含部分url的字符串,例如"google.com"
是否有可能从该字符串获得有效的URI ?
预期的结果将是相同的,你从任何网页浏览器的地址栏中放置google.com。例如http://www.google.com/
最后我想把这个值传递给一个新的Uri对象,这样我就可以在HttpWebRequest中使用它来检索Favicons。
你在找这样的东西吗?
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。