WebBrowser.Navigate(); How to pass ntlm credentials
I have created a web page capture utility is run through an httphandler which can access public sites easily and create screenshots.
Problem: I am trying to access a local Sharepoint site, which requires NTLM credentials in order to view the pages I am attempting to make screenshots of.
When I execute WebBrowser.Navigate(Sharepointsite) I get a 401 challenge to pass through the credentials. Now because this is running as a background service I need to pass through the credentials automatically. At the moment, the browser just hangs and waits for the credentials. I have looked at passing the credentials in the headers which can be passed in the Navigate method but still no luck...
This is my code for the executing function.
ICredentials cred = new NetworkCredential(username, password, domain);
String authorisationHeader = String.Empty;
private bool Ping(string url)
{
try
{
bool status;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Credentials = cred;
req.AllowAutoRedirect = true;
req.ContentType = "text/html";
req.Accept = "*/*";
req.KeepAlive = false;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
status = (resp.StatusCode.ToString() == "OK");
WebHeaderCollection c = resp.Headers;
}
authorisationHeader = req.Headers.GetValues("Authorization")[0];
return status;
}
catch
{
return false;
}
}
public Bitmap GenerateScreenshot(string url, int width, int height)
{
bool Active = Ping(url);
if (Active)
{
// Load the webpage into a WebBrowser control
wb.AllowNavigation = true;
wb.AllowWebBrowserDrop = true;
wb.Navigate(url, null, null, authorisationHeader);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
//HANGS HERE IF THE SITE NEEDS AUTHENTICATION... Credentials aren't being passed through successfully. HELP!
while (!isComplete)
{
Thread.Sleep(0);
}
wb.Dispose();
}
return bitmap;
}
If anyone can help me automatically log in to a site requiring authentication that would be 开发者_JAVA百科amazing! Cheers.
This probably comes back to the IE setting about passing credentials (because the web browser is basically an instance of IE). So I would add this site to the trusted site on the machine and then check the User Authentication -> Logon -> Automatic Logon with current username and password setting in IE for the trusted sites.
精彩评论