【发布时间】:2010-06-17 15:10:31
【问题描述】:
如何在 httpwebresponse 中获取 httponly cookie? 我习惯性地使用 CookieContainer 来获取 httpwebresponse 中的 cookie,但它不适用于 httponly cookie。
还有其他方法可以抓住它们吗?
【问题讨论】:
如何在 httpwebresponse 中获取 httponly cookie? 我习惯性地使用 CookieContainer 来获取 httpwebresponse 中的 cookie,但它不适用于 httponly cookie。
还有其他方法可以抓住它们吗?
【问题讨论】:
是的,可以检索 HTTPOnly cookie,例如从使用 "InternetGetCookieEx" function in the "Wininet.dll" 的客户端程序中检索。 您必须像这样使用 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。
希望对你有帮助!
【讨论】: