我正在尝试通过修改“导航前”事件中的标题来使用WatiN框架更改用户代理字符串。我认为我真的很接近一个解决方案,但出于某种原因,在网址被访问了一段时间后,我被重定向到一个空白页面,其中包含以下代码。
如果我注释掉自定义BeforeNavigate事件,浏览器不会重定向到空白页面,这使我相信我的自定义事件需要稍作修改。你对这个问题有什么想法吗?
要重现此问题,请下载WatiN并运行以下代码:
private SHDocVw.InternetExplorerClass _ieInstance;
private const string UserAgent =
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64)" +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153" +
"Safari/537.36\r\n";
bool _renavigating;
private IE _browser;
private void Form1_Load(object sender, EventArgs e)
{
_ieInstance = _ieInstance = new SHDocVw.InternetExplorerClass();
//_ieInstance.BeforeNavigate2 += BeforeNavigate;
_browser = new IE(_ieInstance);
_browser.GoTo("http://www.procato.com/my+headers/");
}
void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
headers += string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;
_ieInstance.Navigate((string)url,
(string)targetFrameName, (byte[])postData, (string)headers);
}
else
{
_renavigating = false;
}
}
}
@ Noseratio的建议也给了我一个空白页面:
readonly SynchronizationContext _sc = SynchronizationContext.Current;
void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
var newHeaders = string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;
string thatUrl = (string)url;
object thatFlags = flags;
object thatTargetFrameName = targetFrameName;
object thatPostData = postData;
object thatHeaders = (headers != null && headers != Type.Missing &&
headers != System.DBNull.Value) ?
(headers.ToString() + newHeaders) : newHeaders;
_sc.Post(_ =>
{
((SHDocVw.IWebBrowser)pDisp).Navigate(
thatUrl,
ref thatFlags,
ref thatTargetFrameName,
ref thatPostData,
ref thatHeaders);
}, null);
}
else
{
_renavigating = false;
}
}
}
答案 0 :(得分:0)
导航到该页面的请求就足够了。
在这种情况下,我建议您放弃BeforeNavigate2
,只需使用_ieInstance.Navigate
进行导航即可让您的生活更轻松。 e.g:
private void Form1_Load(object sender, EventArgs e)
{
_ieInstance = _ieInstance = new SHDocVw.InternetExplorerClass();
_browser = new IE(_ieInstance);
_ieInstance.Navigate("http://www.procato.com/my+headers/", Headers: UserAgent);
}
procato上显示的结果将是错误的标题,因为加载页面会产生额外的请求,而那些不会有正确的标题。但是,如果您使用像Fiddler2这样的工具,您将看到初始请求具有正确的用户代理标头。