【发布时间】:2016-12-29 12:08:10
【问题描述】:
我需要将自定义用户代理和身份验证令牌插入到从 webview 发出的所有请求中。是否可以拦截从 webview 发出的 HttpRequests?
【问题讨论】:
标签: windows xaml webview win-universal-app
我需要将自定义用户代理和身份验证令牌插入到从 webview 发出的所有请求中。是否可以拦截从 webview 发出的 HttpRequests?
【问题讨论】:
标签: windows xaml webview win-universal-app
在 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);
}
【讨论】: