On Universal Windows 10 Platform, the WebView.NavigateWithHttpRequestMessage
method is the right way.
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
This is due to the infinite navigation will happen if we do navigation in the NavigationStarting
event. We should cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel
property to true.
And we need to add/remove handler for NavigationStarting
event carefully.
Code sample:
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);
}
The screenshot is the log info in Fiddler, the request record in the second red rectangle included the custom header:

I shared my UWP sample in here, you can easily integrate into your Xamarin UWP app.