• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    .net 获取浏览器Cookie(包括HttpOnly)实例分享

    一、接口文件

    复制代码 代码如下:

    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 Dictionarystring, string> GetCookieList(Uri uri, bool throwIfNoCookie)
            {
                Dictionarystring, string> dict = new Dictionarystring, 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");
                Dictionarystring, 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();
            }
        }
    }

    您可能感兴趣的文章:
    • JavaScript获取浏览器信息的方法
    • Js 获取、判断浏览器版本信息的简单方法
    • 获取IE浏览器Cookie信息的方法
    上一篇:asp.net C#生成和解析二维码的实例代码
    下一篇:AspNetPager分页控件定义及应用样式示例介绍
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯 版权所有

    《增值电信业务经营许可证》 苏ICP备15040257号-8

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