2

httpwebresponse で httponly Cookie を取得するにはどうすればよいですか? 私は習慣的に CookieContainer を使用して httpwebresponse で Cookie を取得していますが、httponly Cookie では機能しません。

それらをキャッチする他の方法はありますか?

4

2 に答える 2

6

はい、「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からのものです。

それが役立つことを願っています!

于 2012-09-20T13:10:14.480 に答える
1

CookieContainer から HTTPOnly Cookie を取得することはできません。

MSDNから

...応答で Cookie が返されるようにする場合は、要求と共に送信する CookieContainer を常に作成する必要があります。これは、取得できない HTTPOnly Cookie にも当てはまります。

于 2010-06-17T15:21:01.297 に答える