简体   繁体   English

C#获取httponly cookie

[英]c# Get httponly cookie

How can i get a httponly cookie in a httpwebresponse ? 如何在httpwebresponse中获取httponly cookie? Habitually i use a CookieContainer to get the cookies in a httpwebresponse, but it doesnt work with httponly cookie. 通常,我使用CookieContainer在httpwebresponse中获取cookie,但不适用于httponly cookie。

Is there an other way to catch them ? 还有其他方法可以抓住他们吗?

Yes, it is possible to retrieve a HTTPOnly cookie , for instance from a client program using the "InternetGetCookieEx" function in the "Wininet.dll" . 是的, 可以使用“ Wininet.dll”中“ InternetGetCookieEx”功能从客户端程序中检索HTTPOnly cookie You must use PInvoke code like this : 您必须使用如下的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();
    }
}

The code is from MSDN . 该代码来自MSDN

I hope that helps ! 希望对您有所帮助!

You cannot retrieve HTTPOnly cookies from the CookieContainer. 您无法从CookieContainer检索HTTPOnly cookie。

from MSDN MSDN

...You must always create a CookieContainer to send with a request if you want cookies to be returned on the response. ...如果您想在响应中返回cookie,则必须始终创建一个CookieContainer来发送请求。 This is also true for HTTPOnly cookies, which you cannot retrieve. 对于无法检索的HTTPOnly cookie也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM