我正在创建一个 Windows 窗体应用程序,其中有一个 webbrowser 控件
。
用户使用 webbrowser
登录后,我也想使用 Microsoft.Http.HttpClient
或 HttpWebRequest
或相同的帐户登录类似,它应该类似于 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;
}