2

如何在 httpwebresponse 中获取 httponly cookie?我习惯性地使用 CookieContainer 来获取 httpwebresponse 中的 cookie,但它不适用于 httponly cookie。

有没有其他方法可以抓住它们?

4

2 回答 2

6

是的,可以检索HTTPOnly cookie,例如使用"Wininet.dll" 中的 "InternetGetCookieEx" 函数从客户端程序中检索。您必须像这样使用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

我希望这会有所帮助!

于 2012-09-20T13:10:14.480 回答
1

您无法从 CookieContainer 中检索 HTTPOnly cookie。

来自MSDN

...如果您希望在响应中返回 cookie,则必须始终创建一个 CookieContainer 以随请求一起发送。这也适用于您无法检索的 HTTPOnly cookie。

于 2010-06-17T15:21:01.297 回答