【问题标题】:c# Get httponly cookiec# 获取httponly cookie
【发布时间】:2010-06-17 15:10:31
【问题描述】:

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

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

【问题讨论】:

    标签: c# httponly


    【解决方案1】:

    是的,可以检索 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

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      您无法从 CookieContainer 中检索 HTTPOnly cookie。

      来自MSDN

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

      【讨论】:

      • 这个答案可能已经过时了。 Cookie 对象的最新版本没有此引用文本。
      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 2016-08-03
      • 2020-05-14
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多