我正在尝试通过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());
}
}
为什么会这样?
答案 0 :(得分:54)
试试这个:
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("http://intranet/"),
"NTLM",
new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;