.net WebClient 类的域凭据不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1680718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:31:54 来源:igfitidea点击:
Domain credentials for a WebClient class don't work
提问by agnieszka
I'm trying to get a html source of a website through C# code. When I access the site with windows authentication the following code works:
我正在尝试通过 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());
}
}
when I enter my domain credentials manually i get an "unauthenticated" message:
当我手动输入我的域凭据时,我收到一条“未经身份验证”的消息:
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());
}
}
Why is it so?
为什么会这样?
回答by Darin Dimitrov
Try this:
尝试这个:
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("http://intranet/"),
"NTLM",
new NetworkCredential("username", "pass", "domain"));
client.Credentials = cc;

