码迷,mamicode.com
首页 > Windows程序 > 详细

FiddlerCoreAPI开发(一)源码分析

时间:2017-12-20 21:56:16      阅读:2810      评论:0      收藏:0      [点我收藏+]

标签:hostname   服务器   问题   headers   log   private   not   buffer   uri   

1.前言

前一段时间想利用fiddlercore截取本地HTTPS的流量做一些分析,按照样例代码的注释学习了一下,没搞清楚怎么实现,后来又在网上查了些资料,对HTTPS的处理提及很少,都没有解决我的问题,主要是HTTPS证书的问题,索性自己研究了一下,终于解决了问题。我会在下篇文章中分享下我的思路,本篇文章先简单分析下fiddlercore自带样例的代码,帮助刚接触fiddlercore的人快速入门,如果有说的不对的地方,欢迎批评指正。

2.源码分析

首先从官网下载FiddlerCoreAPI
https://www.telerik.com/purchase/fiddlercore

下载下来是一个安装文件,解压后有demo和FiddlerCoreAPI库,打开样例代码工程,开始分析。

从主函数开始。

List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();

定义了一个fiddler的Session类的List,里面存放的是客户端和服务端的消息。

Fiddler.FiddlerApplication.SetAppDisplayName("FiddlerCoreDemoApp");

命名自己的应用程序。

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

这两句,第一句绑定了用户通知事件的函数,具体什么时候触发没仔细研究,第二句绑定了FiddlerApplication.Log触发的事件(FiddlerCore自己的日志系统),后面打印内容都会用到,总之这两句就是把内容打印在控制台上。

Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
{
    // Console.WriteLine("Before request for:\t" + oS.fullUrl);
    oS.bBufferResponse = false;
    Monitor.Enter(oAllSessions);
    oAllSessions.Add(oS);
    Monitor.Exit(oAllSessions);
    
    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());
    }
};

BeforeRequest,顾名思义,就是在客户端发送请求后拦截之,在此函数中可以获取甚至修改请求的内容。

oS.fullUrl为请求的URL。

bBufferResponse这个属性,要设置成true才可以修改服务器响应的内容。

接下来的if判断,是一个例子,如果你访问https://localhost:7777,他会拦截你的请求,并构造响应报文返回给你,服务端不会收到该请求。

Fiddler.FiddlerApplication.Startup(iPort, oFCSF);

开启FiddlerCore在指定端口的监听。

oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(iSecureEndpointPort, true, sSecureEndpointHostname);

建立在指定端口的HTTPS的监听,这个函数下篇文章中还会说到。

至此,这个样例的主要代码就分析完了,它实现了简单的http请求截获和响应替换,剩余的代码都是些与用户的交互,这里不再赘述。

3.注意

前面代码执行完后,一定要调用Shutdown()函数关闭FiddlerCore应用,不然会导致浏览器还是通过Fiddler代理,上不了网。

Fiddler.FiddlerApplication.Shutdown();

在证书管理器中可以看到FiddlerCore安装了自己的证书。

技术分享图片

阅读样例代码的注释很有帮助,还有FiddlerCore的帮助文档,里面各个函数的功能说的很详细。

FiddlerCoreAPI开发(一)源码分析

标签:hostname   服务器   问题   headers   log   private   not   buffer   uri   

原文地址:http://www.cnblogs.com/realwy/p/8075705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!