如何在C#中使用Fiddlercore捕获http请求?

时间:2014-08-28 05:43:03

标签: c# selenium fiddlercore

我正在尝试使用C#中的fiddlercore捕获请求标头。这是我的代码。我使用selenium进入我想要获取Request header / webforms的网页。我能够访问网页,但无法使用fiddlercore捕获任何内容。我知道我必须使用委托和BeginInvoke方法但是应该如何完成它还不清楚。 我正在使用AfterSessionComplete事件来捕获请求正文。但它是空的。我错过了什么?有人可以帮我解决这个问题吗?谢谢。这是我的代码。

    public void requestURL()
{
        IWebDriver driver = new FirefoxDriver();

        driver.Navigate().GoToUrl("http://www.google.com");            

        IWebElement query = driver.FindElement(By.Name("q"));
        // search Cheese
        query.SendKeys("Cheese");
        //// submit query
        query.Submit();

        // Wait for the page to load, timeout after 10 seconds
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        wait.Until((d) => { return d.Title.StartsWith("Cheese"); });

        // Should see: "Cheese - Google Search"
        Console.WriteLine("Page title is: " + driver.Title);
        Console.WriteLine("URL for page is: " + driver.Url);
    }

    static void Main(string[] args)
    {
        FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.DecryptSSL);
        HttpActions h = new HttpActions();
        h.requestURL();
        FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
        FiddlerApplication.Shutdown();
    }

    static void FiddlerApplication_AfterSessionComplete(Session oSession)
    {
        var s = oSession.GetRequestBodyAsString();
    }

1 个答案:

答案 0 :(得分:2)

  1. 您应该将Selenium设置为通过FiddlerCore代理,您就是这样做的:

    var seleniumProxy = new Proxy { HttpProxy = "localhost:8878", SslProxy = "localhost:8878" };
    var profile = new FirefoxProfile();
    profile.SetProxyPreferences(seleniumProxy);
    var slenium = new FirefoxDriver(profile);
    
  2. 建议,您可以在启动FiddlerCore时设置更多标志,以便将来为您节省一些故障排除:

    const FiddlerCoreStartupFlags fiddlerStartUpFlags = FiddlerCoreStartupFlags.DecryptSSL & FiddlerCoreStartupFlags.AllowRemoteClients & FiddlerCoreStartupFlags.CaptureFTP & FiddlerCoreStartupFlags.ChainToUpstreamGateway & FiddlerCoreStartupFlags.MonitorAllConnections & FiddlerCoreStartupFlags.CaptureLocalhostTraffic;
    
    FiddlerApplication.Startup(8877, fiddlerStartUpFlags);
    
  3. 由于您可能正在使用FiddlerCore + Selenium进行测试,因此您需要添加一些其他内容:

  4. 测试完成后,执行此操作 -

        FiddlerApplication.oProxy.PurgeServerPipePool();//Run this between tests to make sure the new test will start "clean"
    

    在调用FiddlerApplication.Startup(8877,fiddlerStartUpFlags);之前,执行这些 -

        FiddlerApplication.Prefs.SetStringPref("fiddler.config.path.makecert", @"d:\..\Makecert.exe");//To define the MakeCert.exe path manually.
        FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);//Abort session when client abort