How do I authenticate a WebClient request?

smartdirt picture smartdirt · Dec 10, 2009 · Viewed 98.6k times · Source

I am making a call to a page on my site using webclient. I'm trying to get the result of the webpage put into a pdf so I am trying to get a string representation of the rendered page. The problem is that the request is not authenticated so all I get is a login screen. I have sent the UseDefaultCredentials property to true but I still get the same result. Below is a portion of my code:

 WebClient webClient = new WebClient();
 webClient.Encoding = Encoding.UTF8;

 webClient.UseDefaultCredentials = true;
 return Encoding.UTF8.GetString(webClient.UploadValues(link, "POST",form));

Answer

Ryan Alford picture Ryan Alford · Dec 10, 2009

You need to give the WebClient object the credentials. Something like this...

 WebClient client = new WebClient();
 client.Credentials = new NetworkCredential("username", "password");