C# 检查URL是否正常工作或未使用

C# 检查URL是否正常工作或未使用,c#,C#,上面的程序将输出true,但当我将字符串更改为 string url = "www.google.com"; public bool UrlIsValid(string url) { bool br = false; try { IPHostEntry ipHost = Dns.GetHostEntry(url); br = true; }

上面的程序将输出true,但当我将字符串更改为

string url = "www.google.com";

public bool UrlIsValid(string url)
{
    bool br = false;
    try
    {
                    IPHostEntry ipHost =  Dns.GetHostEntry(url);
                                     br = true;
    }
    catch (SocketException)
    {
        br = false;
    }
    return br;
}
我得到的输出为
false


如何获取第二个案例的输出?

Dns.GetHostEntry正在查找域名,而不是url。尝试将字符串转换为URI并首先使用URI.DnsSafeHost

string url = "https://www.google.com";

您可以尝试使用Uri类来解析url字符串

string url = "http://www.google.com";
Uri uri = new Uri(url);
string domain = uri.DnsSafeHost;
使用


您想确保url的主机名是已知的吗?主机提供响应的协议与Dns.GetHostEntry不太相关。
UrlIsValid
的服务目的是什么?消费代码根据结果做出什么决定?检查是否有代理阻止请求。如果页面需要登录,这将不起作用。在这种情况下,您将收到401;但我想这是“工作”的定义问题:)
public bool UrlIsValid(string url) {
   return UrlIsValid(new Uri(url));
}


public bool UrlIsValid(Uri url)
{
    bool br = false;
    try
    {
         IPHostEntry ipHost =  Dns.GetHostEntry(url.DnsSafeHost);
         br = true;
    }
    catch (SocketException)
    {
        br = false;
    }
    return br;
}
Uri siteUri = new Uri("http://www.contoso.com/");
WebRequest wr = WebRequest.Create(siteUri);

// now, request the URL from the server, to check it is valid and works
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
    }
    response.Close();
}