欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net 获取浏览器Cookie(包括HttpOnly)实例分享

程序员文章站 2024-02-27 22:59:39
一、接口文件 复制代码 代码如下:using system; using system.componentmodel; using system.net; using s...

一、接口文件

复制代码 代码如下:

using system;
using system.componentmodel;
using system.net;
using system.runtime.interopservices;
using system.security;
using system.security.permissions;
using system.text;

namespace cookiehandler
{
    internal sealed class inativemethods
    {
        #region enums

        public enum errorflags
        {
            error_insufficient_buffer = 122,
            error_invalid_parameter = 87,
            error_no_more_items = 259
        }

        public enum internetflags
        {
            internet_cookie_httponly = 8192, //requires ie 8 or higher     
            internet_cookie_third_party = 131072,
            internet_flag_restricted_zone = 16
        }

        #endregion

        #region dll imports

        [suppressunmanagedcodesecurity, securitycritical, dllimport("wininet.dll", entrypoint = "internetgetcookieexw", charset = charset.unicode, setlasterror = true, exactspelling = true)]
        internal static extern bool internetgetcookieex([in] string url, [in] string cookiename, [out] stringbuilder cookiedata, [in, out] ref uint pchcookiedata, uint flags, intptr reserved);

        #endregion
    }
}

二、获取cookie类

复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.net;
using system.runtime.interopservices;
using system.security;
using system.security.permissions;
using system.text;

namespace cookiehandler
{
    /// <summary></summary>
    /// 取得webbrowser的完整cookie。
    /// 因为默认的webbrowser1.document.cookie取不到httponly的cookie
    /// ie7不兼容,ie8可以,其它未知
    ///
    public class fullwebbrowsercookie
    {
        public static dictionary<string, string> getcookielist(uri uri, bool throwifnocookie)
        {
            dictionary<string, string> dict = new dictionary<string, string>();
            string cookie = getcookieinternal(uri, throwifnocookie);
            console.writeline("fullwebbrowsercookie - 所有cookie:" + cookie);
            string[] arrcookie = cookie.split(';');
            foreach (var item in arrcookie)
            {
                string[] arr = item.split('=');
                string key = arr[0].trim();
                string val = "";
                if (arr.length >= 2)
                {
                    val = arr[1].trim();
                }

                if (!dict.containskey(key))
                {
                    dict.add(key, val);
                }
            }
            console.writeline("fullwebbrowsercookie - cookie已载入dict,共" + dict.count.tostring() + "项");

            return dict;
        }

        public static string getcookievalue(string key, uri uri, bool throwifnocookie)
        {
            console.writeline("getcookievalue");
            dictionary<string, string> dict = getcookielist(uri, throwifnocookie);

            if (dict.containskey(key))
            {
                return dict[key];
            }
            return "";
        }

        [securitycritical]
        public static string getcookieinternal(uri uri, bool throwifnocookie)
        {
            console.writeline("getcookieinternal");

            uint pchcookiedata = 0;
            string url = uritostring(uri);
            uint flag = (uint)inativemethods.internetflags.internet_cookie_httponly;

            //gets the size of the string builder     
            if (inativemethods.internetgetcookieex(url, null, null, ref pchcookiedata, flag, intptr.zero))
            {
                pchcookiedata++;
                stringbuilder cookiedata = new stringbuilder((int)pchcookiedata);

                //read the cookie     
                if (inativemethods.internetgetcookieex(url, null, cookiedata, ref pchcookiedata, flag, intptr.zero))
                {
                    demandwebpermission(uri);
                    return cookiedata.tostring();
                }
            }

            int lasterrorcode = marshal.getlastwin32error();

            if (throwifnocookie || (lasterrorcode != (int)inativemethods.errorflags.error_no_more_items))
            {
                throw new win32exception(lasterrorcode);
            }

            return null;
        }

        private static void demandwebpermission(uri uri)
        {
            string uristring = uritostring(uri);

            if (uri.isfile)
            {
                string localpath = uri.localpath;
                new fileiopermission(fileiopermissionaccess.read, localpath).demand();
            }
            else
            {
                new webpermission(networkaccess.connect, uristring).demand();
            }
        }

        private static string uritostring(uri uri)
        {
            if (uri == null)
            {
                throw new argumentnullexception("uri");
            }

            uricomponents components = (uri.isabsoluteuri ? uricomponents.absoluteuri : uricomponents.serializationinfostring);
            return new stringbuilder(uri.getcomponents(components, uriformat.safeunescaped), 2083).tostring();
        }
    }
}