WebClient类的域凭据不起作用

时间:2009-11-05 13:52:49

标签: .net

我正在尝试通过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());
                }
            }

为什么会这样?

1 个答案:

答案 0 :(得分:54)

试试这个:

CredentialCache cc = new CredentialCache();
cc.Add(
    new Uri("http://intranet/"), 
    "NTLM", 
    new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;