使用FiddlerCore捕获原始HTTPS请求和响应

时间:2014-12-11 12:12:16

标签: c# fiddler fiddlercore

我有task crate tracer,它将在localhost和SOAP API之间存储带有头和主体的原始HTTP流量。我发现很好的解决方案是FiddlerCore。应用程序仅适用于HTTPS。目前我只得到了我的要求。但是希望看到来自SOAP API的响应。

我在应用程序启动时初始化FolderCore代理:

        CONFIG.bCaptureCONNECT = true;
        CONFIG.IgnoreServerCertErrors = false;
        FiddlerApplication.Prefs.SetStringPref("fiddler.config.path.makecert", @"c:\Program Files (x86)\Fiddler2\Makecert.exe");
        FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
        if (!CertMaker.rootCertExists())
        {
            if (!CertMaker.createRootCert())
            {
                throw new Exception("Unable to create cert for FiddlerCore.");
            }
            X509Store certStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            certStore.Open(OpenFlags.ReadWrite);
            try
            {
                certStore.Add(CertMaker.GetRootCertificate());
            }
            finally
            {
                certStore.Close();
            }
        }

方法AfterSessionComplete:

    private void FiddlerApplication_AfterSessionComplete(Session sess)
    {
        // Ignore HTTPS connect requests
        if (sess.RequestMethod == "CONNECT")
        {
            return; 
        }

        if (sess == null || sess.oRequest == null || sess.oRequest.headers == null)
        {
            return; 
        }
        // Request
        string headers = sess.oRequest.headers.ToString();
        var reqBody = sess.GetRequestBodyAsString();

        // Response
        var resHeaders = sess.oResponse.headers.ToString();
        var resBody = sess.GetResponseBodyAsString();

        // if you wanted to capture the response
        //string respHeaders = session.oResponse.headers.ToString();
        //var respBody = session.GetResponseBodyAsString();

        // replace the HTTP line to inject full URL
        string firstLine = sess.RequestMethod + " " + sess.fullUrl + " " + sess.oRequest.headers.HTTPVersion;
        int at = headers.IndexOf("\r\n");
        if (at < 0)
            return;
        headers = firstLine + "\r\n" + headers.Substring(at + 1);

        string output = headers + "\r\n" +
                        (!string.IsNullOrEmpty(reqBody) ? reqBody + "\r\n" : string.Empty) + "\r\n\r\n";

    }

在web.config中添加:

<defaultProxy>
  <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
</defaultProxy>

1 个答案:

答案 0 :(得分:0)

非常容易。使用sess.oResponse.headers和sess.GetResponseBodyAsString()为此

    var resHeaders = sess.oResponse.headers.ToString();
    var resBody = sess.GetResponseBodyAsString();