![](/img/trans.png)
[英]Is there any way to delete an HttpOnly cookie from C# Selenium tests?
[英]c# Get httponly cookie
如何在httpwebresponse中获取httponly cookie? 通常,我使用CookieContainer在httpwebresponse中获取cookie,但不适用于httponly cookie。
还有其他方法可以抓住他们吗?
是的, 可以使用“ Wininet.dll”中的“ InternetGetCookieEx”功能从客户端程序中检索HTTPOnly cookie 。 您必须使用如下的PInvoke代码:
/// <summary>
/// WinInet.dll wrapper
/// </summary>
internal static class CookieReader
{
/// <summary>
/// Enables the retrieval of cookies that are marked as "HTTPOnly".
/// Do not use this flag if you expose a scriptable interface,
/// because this has security implications. It is imperative that
/// you use this flag only if you can guarantee that you will never
/// expose the cookie to third-party code by way of an
/// extensibility mechanism you provide.
/// Version: Requires Internet Explorer 8.0 or later.
/// </summary>
private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetGetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
ref int size,
int flags,
IntPtr pReserved);
/// <summary>
/// Returns cookie contents as a string
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetCookie(string url)
{
int size = 512;
StringBuilder sb = new StringBuilder(size);
if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
{
if (size < 0)
{
return null;
}
sb = new StringBuilder(size);
if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
{
return null;
}
}
return sb.ToString();
}
}
该代码来自MSDN 。
希望对您有所帮助!
您无法从CookieContainer检索HTTPOnly cookie。
从MSDN
...如果您想在响应中返回cookie,则必须始终创建一个CookieContainer来发送请求。 对于无法检索的HTTPOnly cookie也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.