c# - 获取网络浏览器 cookie 以登录

标签 c# .net cookies webbrowser-control

<分区>

我正在创建一个 Windows 窗体应用程序,其中有一个 webbrowser 控件

用户使用 webbrowser 登录后,我也想使用 Microsoft.Http.HttpClientHttpWebRequest 或相同的帐户登录类似,它应该类似于 PHP 中的 cURL

问题是该网页只允许每个帐户单点登录,如果我使用 HttpClient 登录,它将把网络浏览器踢出。

我想知道的是,是否可以劫持 webbrowser session 或获取 cookies 并将其用于我的 HttpClient 或类似的API

我可以使用 webbrowser.Cookie 获取一些数据,但是如何将其推送到 HttpClient

这种事情是否可能,我可以只获取 cookie 并使用相同的 session ?如果是,怎么办?

最佳答案

从这里得到帮助:

Is it possible to transfer authentication from Webbrowser to WebRequest

Alkampfer 发布解决方案。这正是我所需要的,而且很有效。

此解决方案还使用 Http only cookie。

You can call the GetUriCookieContainer method that returns you a CookieContainer that can be used for subsequent call with WebRequest object.

[DllImport("wininet.dll", SetLastError = true)]
    public static extern bool InternetGetCookieEx(
        string url, 
        string cookieName, 
        StringBuilder cookieData, 
        ref int size,
        Int32  dwFlags,
        IntPtr  lpReserved);

    private const Int32 InternetCookieHttponly = 0x2000;

/// <summary>
/// Gets the URI cookie container.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public static CookieContainer GetUriCookieContainer(Uri uri)
{
    CookieContainer cookies = null;
    // Determine the size of the cookie
    int datasize = 8192 * 16;
    StringBuilder cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
    {
        if (datasize < 0)
            return null;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(datasize);
        if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData, 
            ref datasize, 
            InternetCookieHttponly, 
            IntPtr.Zero))
            return null;
    }
    if (cookieData.Length > 0)
    {
        cookies = new CookieContainer();
        cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
    }
    return cookies;
}

关于c# - 获取网络浏览器 cookie 以登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15049877/

相关文章:

c# - 如何将 Eval() 与包含点 (.) 的列名称一起使用?

c# - 创建 FileStream.Open c# 的接口(interface)

c# - Windows Server 2008 上的正则表达式速度慢

javascript - 删除存储有 'react-cookie' 的 cookie,无论域如何

java - 如何使用Web应用程序和Android应用程序处理Spring MVC后端的安全性?

c# - 在 SQLite 上将表达式结果从浮点转换为小数

c# - 如何为动态 for 循环级别编码?

c# - 返回分层 xml 的节点级别

c# - 如何处理 WCF 上的故障状态? (在 Windows 服务中托管)

c# - 为什么在 Request.Cookies[FormsAuthentication.FormsCookieName] 中找不到 ASPXAUTH cookie?