28

我正在尝试通过 C# 代码获取网站的 HTML 源代码。当我使用 Windows 身份验证访问该站点时,以下代码有效:

using (WebClient client = new WebClient())
            {
                client.Credentials = CredentialCache.DefaultCredentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

当我手动输入我的域凭据时,我收到一条“未经身份验证”的消息。

using (WebClient client = new WebClient())
            {
                NetworkCredential credentials = new NetworkCredential("username", "pass", "domain");
                client.Credentials = credentials;
                using (Stream stream = client.OpenRead("http://intranet/"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    MessageBox.Show(reader.ReadToEnd());
                }
            }

为什么会这样?

4

1 回答 1

56

试试这个:

CredentialCache cc = new CredentialCache();
cc.Add(
    new Uri("http://intranet/"), 
    "NTLM", 
    new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;
于 2009-11-05T14:19:41.373 回答