我使用.NET 3.5在Visual Studio 2008中有一个Windows窗体,它有一个WebBrowser控件.我需要在发送请求之前在导航事件处理程序中分析表单的PostData.有没有办法达到目的?
旧的win32浏览器控件有一个Before_Navigate事件,它将PostData作为其参数之一.新的.NET WebBrowser控件不是这样.
////// Fires before navigation occurs in the given object (on either a window or frameset element). /// /// Object that evaluates to the top level or frame WebBrowser object corresponding to the navigation. /// String expression that evaluates to the URL to which the browser is navigating. /// Reserved. Set to zero. /// String expression that evaluates to the name of the frame in which the resource will be displayed, or Null if no named frame is targeted for the resource. /// Data to send to the server if the HTTP POST transaction is being used. /// Value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code. /// Boolean value that the container can set to True to cancel the navigation operation, or to False to allow it to proceed. private delegate void BeforeNavigate2(object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel); private void Form1_Load(object sender, EventArgs e) { dynamic d = webBrowser1.ActiveXInstance; d.BeforeNavigate2 += new BeforeNavigate2((object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel) => { // Do something with PostData }); }
保留上述内容,但更换:
dynamic d = webBrowser1.ActiveXInstance;
有:
using System.Reflection; ... PropertyInfo prop = typeof(System.Windows.Controls.WebBrowser).GetProperty("ActiveXInstance", BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo getter = prop.GetGetMethod(true); dynamic d = getter.Invoke(webBrowser1, null);
.NET WebBrowser控件不公开该功能.幸运的是,该控件主要是围绕"旧"控件的包装器.这意味着您可以使用以下内容(在向项目添加对SHDocVw的引用之后)订阅您知道并喜欢的BeforeNavigate2事件(?):
Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer) AddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2
...并对该事件中的PostData执行任何操作:
Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _ ByRef Flags As Object, ByRef TargetFrameName As Object, _ ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean) Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData) End Sub
一个重要的警告:WebBrowser.ActiveXInstance属性的文档声明"此API支持.NET Framework基础结构,不应直接在您的代码中使用.".换句话说:您对该属性的使用可能会在将来的任何时候破坏您的应用程序,例如,当Framework人员决定实现自己的浏览器组件时,而不是包装现有的SHDocVw COM组件.
因此,您不希望将此代码放在您发送给很多人的任何内容和/或任何应该继续为许多Framework版本工作的内容中......