CefSharp.WPF监控网络请求
1.CefSharp 117.2.40
2.C#代码
webBrowser.RequestHandler = myRequestHandler;
public class MyRequestHandler : RequestHandler
{
protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture,
bool isRedirect)
{
return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect);
}
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame,
IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
return new MyResourceRequestHandler()
}
}
public class MyResourceRequestHandler : ResourceRequestHandler
{
private MemoryStream memoryStream = new MemoryStream();
protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request)
{
return base.GetResourceHandler(chromiumWebBrowser, browser, frame, request);
}
protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{
if(memoryStream.Length > 0)
{
Console.WriteLine(Encoding.UTF8.GetString(memoryStream.ToArray()));
}
base.OnResourceLoadComplete(chromiumWebBrowser, browser, frame, request, response, status, receivedContentLength);
}
protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
return new StreamResponseFilter(memoryStream)
}
protected override bool OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
return base.OnResourceResponse(chromiumWebBrowser, browser, frame, request, response);
}
}
3.指定CefSharp.BrowserSubprocess.exe目录
CefSettings settings = new CefSettings
{
Locale = "zh-CN",
BrowserSubprocessPath = "D:\\native\\CefSharp.BrowserSubprocess.exe",
};
Cef.Initialize(settings);