c# - 发送 HTTP 到本地 FiddlerCore

标签 c# proxy fiddler fiddlercore

我正在尝试构建一个代理服务器来处理本地请求。
例如 - 捕获 Web 浏览器打印请求并将它们发送到适当的 LAN 打印机。
到目前为止,我的想法是在 Windows 服务中托管 FiddlerCore 引擎。
这是我的代码:

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);
}

我的问题:
ParseRequest 函数可以识别本地请求(即 http://localhost./print?whatever ),但如何阻止代理转发它们(解析并执行打印请求但未获得 404 页面)?

最佳答案

自己找到解决方案:

BeforeRequest 回调中,Fiddler.Session 对象作为参数传递。
当调用其 utilCreateResponseAndBypassServer 函数时,请求不会中继到任何服务器,而是在本地处理。

所以,我的新 ParseRequest 函数如下:

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>");
}

关于c# - 发送 HTTP 到本地 FiddlerCore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21328087/

相关文章:

c# - DP 更改值后启用并聚焦已禁用的控件

c# - 应该使用委托(delegate)的一些常见场景是什么?

objective-c - 如何以编程方式设置代理设置

c# - 使用网络服务时需要代理身份验证错误

protocol-buffers - 让 Fiddler 理解(即解码)使用 Protocol Buffer 编码的 HTTP 请求/响应

c# - 在一个 DLL 中出现 EntryPointNotFoundException 而在另一个 DLL 中似乎正常

c# - 如何使用 C# 对 Intel Xeon Phi 进行编程?

java - Java 中的代理具有动态接口(interface)

ssl - Fiddler 访问 HTTPS 页面失败

c# - SSL在用fiddler修改请求时收到超过最大允许长度的记录