WinForms WebBrowser control detect redirections
Is there any way to detect 302 redirects within the web browser co开发者_如何转开发ntrol that I don't know of? Maybe some kind of magic with the underlying unmanaged control?
No, it's not possible with the normal WebBrowser control. Doing anything with the underlying unmanaged control looks very complex, if that's what you're after you could have a look at http://www.codeproject.com/KB/miscctrl/csEXWB.aspx though:
csEXWB is a C# .NET 2.0 control that creates, hosts and sinks the events of the original Webbrowser control (Not .NET or any other wrapper). Advanced customization and total control over the Webbrowser control are achieved via implementation of a number of interfaces, along with the addition of many methods, properties, events and a COM library.
That includes being able to view page headers, which is what you'd need to do to detect the HTTP redirect.
I was able to detect the redirect within the NavigateError event. The statuscode will be 301 or 302. I set a flag that a redirection is to occur. Then in the navigatecomplete2 event, the URL is the redirection URL. In that event handler I check my redirection flag, and if true, clear the redirect flag and navigate again to the new URL. This should work for multiple redirects. This is VB6 code, but should work in theory for any WebBrowser implementation.
Dim m_isRedirected as boolean
...
Private Sub WebBrowser1_NavigateComplete2(ByVal pDisp As Object, URL As Variant)
If m_isRedirected Then
m_isRedirected = False 'clear the flag in case another redirect occurs
WebBrowser1.Navigate2 URL
End If
End Sub
Private Sub WebBrowser1_NavigateError(ByVal pDisp As Object, URL As Variant, Frame As Variant, StatusCode As Variant, Cancel As Boolean)
If StatusCode = 301 Or StatusCode = 302 Then m_isRedirected = True
End Sub
I found a nice workaround... what you can do is capture/overload the webbrowser.OnNavigating and OnNavigated events.
Normally when navigating both the OnNavigating and OnNavigated events get called. However whenever a redirect occurs the OnNavigated is called, but NOT the OnNavigating event.
so basically I'm using a counter that is reset in the OnNavigating event to 0. in the OnNavigating i'm increasing the counter by 1.
in the OnDocumentCompleted event i will check the counter: if counter == 1, no redirect occured if counter> 1, redirects have occured.
so far this trick seems to work for me.
Using the WebBrowser control in WPF, you can look for the Navigating event. That won't give you the status codes, but you can see the URLs that the web browser is redirected to, so should be able to figure out when a redirection happens. I'm not that familiar with WinForms, but it may well work in a similar fashion.
private void Browser_Navigating(object sender, NavigatingCancelEventArgs e)
{
System.Diagnostics.Trace.WriteLine(e.Uri);
}
精彩评论