WebBrowser.Navigate();如何传递ntlm凭据

时间:2011-02-17 10:30:10

标签: c# winforms webbrowser-control windows-authentication ntlm

我创建了一个网页捕获实用程序,它通过httphandler运行,可以轻松访问公共网站并创建屏幕截图。

问题:我正在尝试访问本地Sharepoint站点,该站点需要NTLM凭据才能查看我尝试制作屏幕截图的页面。

当我执行WebBrowser.Navigate(Sharepointsite)时,我会通过凭据获得401质询。现在因为它作为后台服务运行,我需要自动传递凭据。目前,浏览器只是挂起并等待凭据。我已经看过在头文件中传递凭据,这些凭证可以在Navigate方法中传递,但仍然没有运气......

这是执行功能的代码。

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;
}

如果有人可以帮助我自动登录到需要身份验证的网站,这将是惊人的!欢呼声。

1 个答案:

答案 0 :(得分:3)

这可能会回到关于传递凭据的IE设置(因为Web浏览器基本上是IE的一个实例)。因此,我会将此站点添加到计算机上的受信任站点,然后检查用户身份验证 - >登录 - >自动登录,在IE中为受信任的站点设置当前用户名和密码。