开发者

Domain credentials for a WebClient class don't work

开发者 https://www.devze.com 2022-12-10 09:53 出处:网络
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:

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:

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?


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消