c#获取httponly cookie

标签 c# httponly

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

还有其他方法可以捕获它们吗?

最佳答案

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

希望对您有所帮助!

关于c#获取httponly cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3062925/

相关文章:

google-app-engine - 使用 Play Framework 和 Google App Engine 的 HttpOnly/secure cookies

c# - Linq-to-Entities 动态排序

c# - Azure 服务总线 - 创建队列时出现无效授权 token 签名错误

c# - 字符串和数字条件的最佳实践

java - 使用 Apache 即时向 cookie 添加 HttpOnly 标志?

asp.net - 到底如何在 ASP.NET 中配置 httpOnlyCookies?

c# - 如何使用 Rg.Plugins.Popup 将 XAML 和模板合并到一个 C# 模板中?

c# - 在本地使用 SQL Server CE 并首先在生产 Entity Framework 代码上使用 SQL Server 2008?

web-services - 使用 HttpOnly cookie 注销

javascript - phonegap 应用程序中的 document.cookie 为空