拦截Webview请求Xaml

时间:2016-12-29 12:08:10

标签: windows xaml webview win-universal-app

我需要将自定义用户代理和身份验证令牌插入到从webview制作的所有请求中。是否可以拦截从webview中发出的HttpRequests?

1 个答案:

答案 0 :(得分:0)

在UWP中,我们应该能够使用WebView.NavigateWithHttpRequestMessage方法将WebView导航到带有POST请求和HTTP标头的URI。

WebView中有一个NavigationStarting事件,它发生在WebView导航到新内容之前。因此,我们应该将WebViewNavigationStartingEventArgs.Cancel属性设置为true以取消导航。

例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
    NavigateWithHeader(new Uri("http://www.whoishostingthis.com/tools/user-agent/"));
}

private void NavigateWithHeader(Uri uri)
{
    var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri);
    string ua = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";
    requestMsg.Headers.Add("User-Agent", ua);
    MyWebView.NavigateWithHttpRequestMessage(requestMsg);
    MyWebView.NavigationStarting += Wb_NavigationStarting;
}

private void Wb_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    MyWebView.NavigationStarting -= Wb_NavigationStarting;
    args.Cancel = true;
    NavigateWithHeader(args.Uri);
}