返回首页
当前位置: 主页 > 网络编程 > .Net实例教程 >

使用FiddlerCore来截取替换Http请求中的网页内容

时间:2012-02-11 18:35来源:知行网www.zhixing123.cn 编辑:麦田守望者

做过测试的应该都知道Fiddler,它可以很方便截取Internet上的网页替换成本地的,或者修改其中的一部分内容后呈现。简单地说就是可能监测所有HTTP连接,设置断点,胡乱修改。是测试调试的一件利器。
使用Fiddler的开放组件,我们可以将其集成到自己的程序中,如生成flash/silverlight所需要的crossdomain.xml,clientaccesspolicy.xml安全文件等:
Fiddler的API: http://www.fiddler2.com/fiddler/dev/ScriptSamples.asp

下面是一个小例子:自动生成所有的silverlight安全策略文件:

using System;
using Fiddler;

namespace AccessPolicyTool
{
class Program
{
const string PolicyXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"">
<domain uri=""http://*""/>
</allow-from>
<grant-to>
<resource path=""/"" include-subpaths=""true""/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";

//find and replace the client access policy file.
static void Main(string[] args)
{
//List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();

Fiddler.FiddlerApplication.BeforeRequest += new SessionStateHandler(FiddlerApplication_BeforeRequest);
Fiddler.FiddlerApplication.BeforeResponse += new Fiddler.SessionStateHandler(FiddlerApplication_BeforeResponse);

Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);
Console.ReadKey();
Fiddler.FiddlerApplication.Shutdown();
}

static void FiddlerApplication_BeforeRequest(Session oSession)
{
Console.WriteLine("FiddlerApplication_BeforeRequest");

if (oSession.fullUrl.IndexOf("clientaccesspolicy.xml") > 0)
{
oSession.bBufferResponse = true;
}
}

//find and replace the client access policy file.
static void FiddlerApplication_BeforeResponse(Fiddler.Session oSession)
{
if (oSession.fullUrl.IndexOf("clientaccesspolicy.xml") > 0)
{
Console.WriteLine(oSession.fullUrl);

oSession.utilDecodeResponse();
oSession.utilSetResponseBody(PolicyXml);

oSession.oResponse.headers.HTTPResponseCode = 200;
oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
oSession.oResponse.headers["Content-Type"] = "text/xml";
oSession.oResponse.headers.Remove("WWW-Authenticate");
}
}
}
}
 

------分隔线----------------------------
标签(Tag):C# C#实例教程 c#基础教程 C#源代码 c#技巧
------分隔线----------------------------
推荐内容
猜你感兴趣