Question

I'm tring to build a proxy server to handle local request.
For example - capture web browser printing request and sending them to the appropriate LAN printer.
My idea so far is to host the FiddlerCore engine in a Windows Service.
This is my code:

private static void Main()
{
    FiddlerApplication.OnNotification += (sender, e) => Console.WriteLine("** NotifyUser: " + e.NotifyString);
    FiddlerApplication.Log.OnLogString += (sender, e) => Console.WriteLine("** LogString: " + e.LogString);
    FiddlerApplication.BeforeRequest += oSession => { Console.WriteLine("Before request for:\t" + oSession.fullUrl); oSession.bBufferResponse = true; ParseRequest(oSession); };
    FiddlerApplication.BeforeResponse += oSession => Console.WriteLine("{0}:HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl);
    FiddlerApplication.AfterSessionComplete += oSession => Console.WriteLine("Finished session:\t" + oSession.fullUrl);

    Console.CancelKeyPress += Console_CancelKeyPress;
    Console.WriteLine("Starting FiddlerCore...");
    CONFIG.IgnoreServerCertErrors = true;
    FiddlerApplication.Startup(8877, true, true);
    Console.WriteLine("Hit CTRL+C to end session.");

    Object forever = new Object();
    lock (forever)
    {
        Monitor.Wait(forever);
    }
}

private static void ParseRequest(Session oSession)
{
    switch (oSession.host)
    {
        case "localhost.":
            Console.WriteLine("Handling local request...");
            break;
    }
}

private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Shutting down...");
    FiddlerApplication.Shutdown();
    Thread.Sleep(750);
}

My question:
The ParseRequest function can recognize local requests (i.e. http://localhost./print?whatever), but how can I stop the proxy from relaying them forward (parsing and executing the print request but not getting the 404 page)?

Was it helpful?

Solution

Found the solution myself:

In the BeforeRequest callback, a Fiddler.Session object is passed as an argument.
When calling its utilCreateResponseAndBypassServer function, the request is not relayed to any server but handled locally.

So, my new ParseRequest function is as follow:

private static void ParseRequest(Session oSession)
{
    if (oSession.hostname != "localhost") return;

    Console.WriteLine("Handling local request...");
    oSession.bBufferResponse = true;
    oSession.utilCreateResponseAndBypassServer();
    oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
    oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
    oSession.oResponse["Cache-Control"] = "private, max-age=0";
    oSession.utilSetResponseBody("<html><body>Handling local request...</body></html>");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top