在Web服务器WebBrowser控件不是从网站的Cookie返回(WebBrowser contr

2019-09-29 23:36发布

我试图去一个HTTPS的网站从WebBrowser控件的Web应用程序,从网站上获取一些基本信息(该网站不具备Web服务或在这一点上任何其他API)当我这样做从IIS快递我能够连接登录和切换不同页面,就像我做从网络浏览器对系统的一切,当直接连接工作正常。

大多数开发系统如Windows 10或Windows Server 2016,我可以发布的Web应用程序,连接到Web应用程序,然后通过Web应用程序连接到该网站,登录并加载其他页面的一切工作正常。 但…。 当我部署到GoDaddy的,并通过应用程序连接到网站,我能够成功登录,但是,当我浏览到另一个网页,我重定向到登录页面。

我注意到,我没有回去过上GoDaddy的应用去当任何JSESSION cookies,但我让他们在所有的其他成功案例。 我收到JSESSON饼干我在目标位点登录之前: http://www.altavista.com/但返回的连接饼干应该足够任何网站。 我已经改变了用户代理桌面上我有同样的代理和连接,仍然得到GoDaddy的相同的结果。

我曾尝试在GoDaddy的网站,是受SSL保护的(HTTPS)和那些不只是(HTTP)。 希望有人已经使用WebBrowser控件之前遇到这种类型的问题?

下面的代码的测试片段(正如你可能会注意到我已经尝试了很多东西摸不着头脑CookiePresistance,清除Cookie,JScript的清除状态等:

public static class NativeMethods
{
    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
                                                 IntPtr lpBuffer, int lpdwBufferLength);

    public static void SuppressCookiePersist()
    {
        int dwOption = 81; //INTERNET_OPTION_SUPPRESS_BEHAVIOR
        int option = 3; // INTERNET_SUPPRESS_COOKIE_PERSIST

        IntPtr optionPtr = Marshal.AllocHGlobal(sizeof(int));
        Marshal.WriteInt32(optionPtr, option);

        bool x = InternetSetOption(IntPtr.Zero, dwOption, optionPtr, sizeof(int));
        Marshal.FreeHGlobal(optionPtr);
    }
    public static void EnableCookiePersist()
    {
        int dwOption = 81; //INTERNET_OPTION_SUPPRESS_BEHAVIOR
        int option = 4; // INTERNET_SUPPRESS_COOKIE_POLICY ignores policy and allows cookies to be set https://msdn.microsoft.com/en-us/library/windows/desktop/aa385328(v=vs.85).aspx

        IntPtr optionPtr = Marshal.AllocHGlobal(sizeof(int));
        Marshal.WriteInt32(optionPtr, option);

        InternetSetOption(IntPtr.Zero, dwOption, optionPtr, sizeof(int));
        option = 1;
        Marshal.WriteInt32(optionPtr, option);
        InternetSetOption(IntPtr.Zero, dwOption, optionPtr, sizeof(int));
        Marshal.FreeHGlobal(optionPtr);
    }
    public static void ClearBrowserSession()
    {
        int dwOption = 42; //INTERNET_OPTION_END_BROWSER_SESSION

        InternetSetOption(IntPtr.Zero, dwOption, IntPtr.Zero, 0);

    }
}   

public partial class TestStub: System.Web.UI.Page
{
    protected void btnNavigate_Click(object sender, EventArgs e)
    {
        NativeMethods.EnableCookiePersist();
        if(tbUrl.Text == "")
        {
            Client_Alert("Please enter url");
            return;
        }
        if (tbUserAgent.Text == "")
            tbUserAgent.Text = CurrentUserAgent;
        object o = tbUrl.Text;

        var t = new Thread((ParameterizedThreadStart)GetPage);
        t.SetApartmentState(ApartmentState.STA);
        t.Start(o);

        GettingPage = true;
        while (GettingPage == true)
            Thread.Sleep(500);
        t.Join();
        return;
    }

    private void GetPage(object o)
    {

        StringBuilder SB = new StringBuilder();
        DirectorBrowser = new WebBrowser();

        NativeMethods.ClearBrowserSession();
        DirectorBrowser.ScrollBarsEnabled = false;
        DirectorBrowser.ScriptErrorsSuppressed = true;
        DirectorBrowser.AllowNavigation = true;
        DirectorBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; '); for (e = 0; e < a.length && a[e]; e++) { f++; for (b = '.' + location.host; b; b = b.replace(/^ (?:% 5C.|[^% 5C.] +) /, '')){ for (c = location.pathname; c; c = c.replace(/.$/, '')) { document.cookie = (a[e] + '; domain=' + b + '; path=' + c + '; expires=' + new Date((new Date()).getTime() - 1e11).toGMTString()); } }}})())");
        NativeMethods.EnableCookiePersist();

        DirectorBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_NoticeCompleted);
        Uri url = new Uri((string)o);
        DirectorBrowser.Navigate(url, null, null, "User-Agent: " + tbUserAgent.Text);

        GettingPage = true;

        while (GettingPage == true)
        {
            System.Windows.Forms.Application.DoEvents();
            Thread.Sleep(500);
        }
    }
    private void browser_NoticeCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if (GettingPage == true)
        {
            HtmlElement body = DirectorBrowser.Document.Body;
            HtmlElementCollection inputs = DirectorBrowser.Document.GetElementsByTagName("INPUT");
            HtmlElementCollection forms = DirectorBrowser.Document.Forms;
            body = DirectorBrowser.Document.Body;
            string webResults = body.InnerHtml;
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(webResults);
            htmlDoc.OptionFixNestedTags = true;

            tbMaintenanceResults.Text = "Cookies: <br>" + DirectorBrowser.Document.Cookie + "<br>" + body.InnerHtml;
            GettingPage = false;
        }
        else
        {
            GettingPage = false;
        }
    }
}

Answer 1:

添加自定义安全管理器,并且仍然没有成功后:

public partial  class InternetSecurityManager : IInternetSecurityManager
{
    private static Guid _CLSID_SecurityManager = new Guid("7b8a2d94-0ac9-11d1-896c-00c04fb6bfc4");
    private static string[] ZoneNames = new[] { "Local", "Intranet", "Trusted", "Internet", "Restricted" };public static string GetUrlZone(string url)
    { 
        Type t = System.Type.GetTypeFromCLSID(_CLSID_SecurityManager);
        IInternetSecurityManager securityManager = (IInternetSecurityManager)System.Activator.CreateInstance(t);
        try
        {
            uint zone = 0;
            int hResult = securityManager.MapUrlToZone(url, ref zone, 0);
            if (hResult != 0)
                throw new COMException("Error calling MapUrlToZone, HRESULT = " + hResult.ToString("x"), hResult);

            if (zone < ZoneNames.Length)
                return ZoneNames[zone];
            return "Unknown - " + zone;
        }
        finally
        {
            Marshal.ReleaseComObject(securityManager);
        }
    }
    public static void GetUrlZoneCookiesPermissions(string url)
    {
        Type t = System.Type.GetTypeFromCLSID(_CLSID_SecurityManager);
        IInternetSecurityManager securityManager = (IInternetSecurityManager)System.Activator.CreateInstance(t);
        try
        { 
            uint puaf = 0x00000040;  //PUAF TRUSTED
            byte obptr = 0;
            int hResult = securityManager.ProcessUrlAction(url, 0x00001A06, out obptr, 1, 0, 0, puaf, 0);
            //hResult = securityManager.ProcessUrlAction(url, 0x00001A10, out obptr, 1, 0, 0, puaf, 0);
            hResult = securityManager.ProcessUrlAction(url, 0x00001A03, out obptr, 1, 0, 0, puaf, 0);
            return;
        }
        finally
        {
            Marshal.ReleaseComObject(securityManager);
        }
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int SetSecuritySite([In] IntPtr pSite)
    {
        return Convert.ToInt32( 0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int GetSecuritySite([Out] IntPtr pSite)
    {
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int MapUrlToZone([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, ref uint pdwZone, uint dwFlags)
    {
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int GetSecurityId([MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pbSecurityId, ref uint pcbSecurityId, uint dwReserved)
    {
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int ProcessUrlAction([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, uint dwAction, out byte pPolicy, uint cbPolicy, byte pContext, uint cbContext, uint dwFlags, uint dwReserved)
    {

                pPolicy = 0;
                return 0;// S_OK;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int QueryCustomPolicy([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, ref Guid guidKey, ref byte ppPolicy, ref uint pcbPolicy, ref byte pContext, uint cbContext, uint dwReserved)
    {
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int SetZoneMapping(uint dwZone, [In, MarshalAs(UnmanagedType.LPWStr)] string lpszPattern, uint dwFlags)
    {
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }

    [return: MarshalAs(UnmanagedType.I4)]
    public int GetZoneMappings(uint dwZone, out UCOMIEnumString ppenumString, uint dwFlags)
    {
        ppenumString = null;
        return Convert.ToInt32(0x800C0011); //INET_E_DEFAULT_ACTION;
    }


}

[ComImport, GuidAttribute("79EAC9EE-BAF9-11CE-8C82-00AA004BA90B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInternetSecurityManager
{
    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int SetSecuritySite([In] IntPtr pSite);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int GetSecuritySite([Out] IntPtr pSite);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int MapUrlToZone([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
             ref UInt32 pdwZone, UInt32 dwFlags);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int GetSecurityId([MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
              [MarshalAs(UnmanagedType.LPArray)] byte[] pbSecurityId,
              ref UInt32 pcbSecurityId, uint dwReserved);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int ProcessUrlAction([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
             UInt32 dwAction, out byte pPolicy, UInt32 cbPolicy,
             byte pContext, UInt32 cbContext, UInt32 dwFlags,
             UInt32 dwReserved);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int QueryCustomPolicy([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
              ref Guid guidKey, ref byte ppPolicy, ref UInt32 pcbPolicy,
              ref byte pContext, UInt32 cbContext, UInt32 dwReserved);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int SetZoneMapping(UInt32 dwZone,
               [In, MarshalAs(UnmanagedType.LPWStr)] string lpszPattern,
               UInt32 dwFlags);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int GetZoneMappings(UInt32 dwZone, out UCOMIEnumString ppenumString,
            UInt32 dwFlags);


    }
}

我发现这个职位从2006年: http://www.tech-archive.net/Archive/InetSDK/microsoft.public.inetsdk.programming.webbrowser_ctl/2006-03/msg00073.html显然Cookies没有通过安全管理,他们处理由区域经理不能自定义的处理方式。 解决这个问题的唯一方法是增加额外的区域为您的特定需求到注册表中。 不幸的是没有办法当你使用WebBrowser控件从代码中做到这一点。 如果你的网站是在Web场托管你没有访问注册表,以另一种方式将需要(可能是IE插件或部署在那里您可以访问和权限设置默认浏览器,你的服务器上需要)



文章来源: WebBrowser control in web server not returning Cookie from Website