在UWP中设置自定义WebView标头

这似乎与其他类似问题重复,但它们是旧线程,而不是Windows UWP应用程序特有的。

我无法在WebView中设置自定义标头,因此WebView中加载的URL可能对我有用。

我见过许多论坛提供的解决方案就像使用HttpClient / WebRequest一样使用标题但是在我的情况下不起作用,url使用Javascript进行重定向,在重定向之前需要很少的自定义标头来正确加载。

此外, WebView.NavigateWithHttpRequestMessage不太适合回发,我需要每个请求的标头,包括Web视图中的 javascript重定向URL。

我可以使用Renderers在Xamarin.Droid项目中设置自定义标题,但我找不到任何UWP Windows.UI.Xaml.Controls.WebView解决方案。

在Universal Windows 10 Platform上, WebView.NavigateWithHttpRequestMessage方法是正确的方法。

一个。 我需要每个请求的标头,包括Web视图中的javascript重定向URL。

湾 这没有解决我的问题,因为在设置头文件后多次调用OnWebViewNavigationStarting方法并且App会自动崩溃并出现System.StackOverflowException错误

这是因为如果我们在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); } 

屏幕截图是Fiddler中的日志信息,第二个红色矩形中的请求记录包括自定义标头:

在此处输入图像描述

我在这里分享了我的UWP示例 ,您可以轻松地集成到您的Xamarin UWP应用程序中。

使用Xamarin标签,看起来你正在使用Xamarin.Forms,因此下面的答案是关于Xamarin.Forms。 但是,代码也适用于UWP中的WebView。

您可以尝试为WebView创建自定义渲染器,然后尝试使用相同的WebView.NavigateWithHttpRequestMessage。

在导航之前,您可以尝试像这样设置标题:

 var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, new Uri("https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending")); requestMsg.Headers.Add("User-Name", "AnubhavRanjan"); Control.NavigateWithHttpRequestMessage(requestMsg); 

上面的Uri可以根据您的要求进行设置。

如果请求多次发生,您始终可以为NavigationStarting事件设置委托并在方法中处理它。

 Control.NavigationStarting += OnWebViewNavigationStarting