我无法在WebView中设置自定义标头,因此WebView中加载的URL可能对我有用.
我见过许多论坛提供解决方案,比如使用带有标头的HttpClient / WebRequest但是在我的情况下不起作用,用于重定向的Web地址使用Javascript,在重定向之前,它需要很少的自定义标头才能正确加载.
此外WebView.NavigateWithHttpRequestMessage不太合适,因为它将回发,我需要每个请求的标题,包括web View中的javascript重定向的URL.
我可以使用Renderers在Xamarin.Droid项目中设置自定义标题,但我找不到任何UWP Windows.UI.Xaml.Controls.WebView的解决方案.
解决方法
WebView.NavigateWithHttpRequestMessage
方法是正确的方法.
a. I need the headers for each request including javascript redirected URLs in web View.
b. This didn’t resolve my issue as after setting the headers the
OnWebViewNavigationStarting
method is called multiple times and App crashes automatically with System.StackOverflowException error
这是因为如果我们在NavigationStarting事件中进行导航,将会发生无限导航.我们应该通过将WebViewNavigationStartingEventArgs.Cancel
属性设置为true来取消此事件的处理程序中的导航.
我们需要仔细添加/删除NavigationStarting事件的处理程序.
代码示例:
private void NavigateWithHeader(Uri uri) { var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get,uri); requestMsg.Headers.Add("User-Name","Franklin Chen"); wb.NavigateWithHttpRequestMessage(requestMsg); wb.NavigationStarting += Wb_NavigationStarting; } private void Button_Click(object sender,RoutedEventArgs e) { NavigateWithHeader(new Uri("http://openszone.com/RedirectPage.html")); } private void Wb_NavigationStarting(WebView sender,WebViewNavigationStartingEventArgs args) { wb.NavigationStarting -= Wb_NavigationStarting; args.Cancel = true;//cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true NavigateWithHeader(args.Uri); }