2010-06-17 78 views
2

如何在httpwebresponse中獲取httponly cookie? 通常我使用CookieContainer來獲取httpwebresponse中的cookie,但它不適用於httponly cookie。c#獲取httponly cookie

是否有其他方法來捕捉它們?

回答

1

您無法從CookieContainer檢索HTTPOnly Cookie。

MSDN

...你必須創建的CookieContainer與發送一個請求,如果你想餅乾要在響應中返回。 HTTPOnly Cookie也是如此,您無法檢索它。

+0

此答案可能已過時。 ['Cookie'](http://msdn.microsoft.com/zh-cn/library/system.net.cookie(v = vs.110).aspx)對象的最新版本沒有此引用文本。 – 2014-02-17 18:38:19

5

是的,這是可能從使用"InternetGetCookieEx" function in the "Wininet.dll"客戶端程序檢索中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

我希望有幫助!