如何通过fiddlercore捕获https响应?

时间:2017-03-10 11:18:41

标签: c# wpf https fiddlercore

我已下载fiddlercore DEMO,我尝试在我的应用程序中使用它依赖于WPF,然后我有一个问题,在我的应用程序中我无法捕获https响应资源?  enter image description here

我的代码就在下面:

    using Fiddler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;

namespace operateToolWPF.Utils
{
    public class MyFiddler
    {
        static Proxy oSecureEndpoint;
        static string sSecureEndpointHostname = "localhost";
        static int iSecureEndpointPort = 7777;
        public List<Fiddler.Session> oAllSessions { get; set; }


        public  void DoQuit()
        {
            if (null != oSecureEndpoint) oSecureEndpoint.Dispose();
            Fiddler.FiddlerApplication.Shutdown();
            //Thread.Sleep(500);
        }
        private  string CalcResponseSize(Session oS)
        {
            if (null == oS.oResponse) return String.Empty;
            var cBytesOut = 0;

            if (null != oS.responseBodyBytes) cBytesOut += oS.responseBodyBytes.Length;
            if ((null != oS.oResponse) && (null != oS.oResponse.headers)) cBytesOut +=
               oS.oResponse.headers.ByteCount();
            return cBytesOut.ToString();
        }

        public  void WriteSessionList(List<Fiddler.Session> oAllSessions)
        {
            ConsoleColor oldColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Session list contains...");
            try
            {
                Monitor.Enter(oAllSessions);
                foreach (Session oS in oAllSessions)
                {
                    Console.Write(String.Format("{0} {1} {2} {3} {4}  {5}  {6}\n", oS.id, oS.oRequest.headers.HTTPMethod, oS.fullUrl, oS.responseCode, oS.oResponse.MIMEType, (oS.Timers.ClientBeginResponse - oS.Timers.ClientBeginRequest), CalcResponseSize(oS)));
                }
            }
            finally
            {
                Monitor.Exit(oAllSessions);
            }
            Console.WriteLine();
            Console.ForegroundColor = oldColor;
        }


        public void DoFiddler()
        {
            oAllSessions = new List<Fiddler.Session>();
            //if (!Fiddler.CertMaker.rootCertExists())
            //{
            //    if (!Fiddler.CertMaker.createRootCert())
            //    {
            //        throw new Exception("Unable to create cert for FiddlerCore.");
            //    }
            //}

            //if (!Fiddler.CertMaker.rootCertIsTrusted())
            //{
            //    if (!Fiddler.CertMaker.trustRootCert())
            //    {
            //        throw new Exception("Unable to install FiddlerCore's cert.");
            //    }
            //}

            #region AttachEventListeners
            Fiddler.FiddlerApplication.OnNotification += delegate(object sender, NotificationEventArgs oNEA) { 
                Console.WriteLine("** NotifyUser: " + oNEA.NotifyString); 
            };
            Fiddler.FiddlerApplication.Log.OnLogString += delegate(object sender, LogEventArgs oLEA) { 
                Console.WriteLine("** LogString: " + oLEA.LogString); 
            };

            Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Fiddler.FiddlerApplication.BeforeRequest");
                oS.bBufferResponse = true;
                Monitor.Enter(oAllSessions); 
                oAllSessions.Add(oS);
                //Console.Write(String.Format("{0} {1} {2} {3} {4}  {5}  {6}\n", oS.id, oS.oRequest.headers.HTTPMethod, oS.fullUrl, oS.responseCode, oS.oResponse.MIMEType, (oS.Timers.ClientBeginResponse - oS.Timers.ClientBeginRequest), CalcResponseSize(oS)));
                Monitor.Exit(oAllSessions);
                oS["X-AutoAuth"] = "(default)";
                if ((oS.oRequest.pipeClient.LocalPort == iSecureEndpointPort) && (oS.hostname == sSecureEndpointHostname))
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.oResponse.headers.SetStatus(200, "Ok");
                    oS.oResponse["Content-Type"] = "text/html; charset=UTF-8";
                    oS.oResponse["Cache-Control"] = "private, max-age=0";
                    oS.utilSetResponseBody("<html><body>Request for httpS://" + sSecureEndpointHostname + ":" + iSecureEndpointPort.ToString() + " received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
                }
            };

            Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
            {
                //Console.WriteLine("Fiddler.FiddlerApplication.AfterSessionComplete");
                //Console.Title = ("Session list contains: " + oAllSessions.Count.ToString() + " sessions");
                //DoQuit();
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            // See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that...
            //
            #endregion AttachEventListeners
            string sSAZInfo = "NoSAZ";
#if SAZ_SUPPORT
            sSAZInfo = Assembly.GetAssembly(typeof(Ionic.Zip.ZipFile)).FullName;

            DNZSAZProvider.fnObtainPwd = () =>
            {
                Console.WriteLine("Enter the password (or just hit Enter to cancel):");
                string sResult = Console.ReadLine();
                Console.WriteLine();
                return sResult;
            };

            FiddlerApplication.oSAZProvider = new DNZSAZProvider();
#endif

            Console.WriteLine(String.Format("Starting {0} ({1})...", Fiddler.FiddlerApplication.GetVersionString(), sSAZInfo));
            Fiddler.CONFIG.IgnoreServerCertErrors = false;
            FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

            FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
            int iPort = 8877;
            Fiddler.FiddlerApplication.Startup(iPort, oFCSF);
            FiddlerApplication.Log.LogFormat("Created endpoint listening on port {0}", iPort);

            FiddlerApplication.Log.LogFormat("Starting with settings: [{0}]", oFCSF);
            FiddlerApplication.Log.LogFormat("Gateway: {0}", CONFIG.UpstreamGateway.ToString());

            oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(iSecureEndpointPort, true, sSecureEndpointHostname);
            if (null != oSecureEndpoint)
            {
                FiddlerApplication.Log.LogFormat("Created secure endpoint listening on port {0}, using a HTTPS certificate for '{1}'", iSecureEndpointPort, sSecureEndpointHostname);
            }


        }
    }
}
谁可以帮助我?谢谢!

1 个答案:

答案 0 :(得分:0)

我希望这解决所有问题在这个演示应用程序中他明确解释了如何跟踪HTTP和HTTPS请求。对于HTTP您可以直接监听AfterSessionComplete事件但是对于HTTPS,您需要安装Fiddler核心证书这个 https://weblog.west-wind.com/posts/2014/jul/29/using-fiddlercore-to-capture-http-requests-with-net