Search code examples
c#.netwinformswebview2

Edit HTTP Request header with WebView2


I am using the new WebView2 control that has recently been released for .NET and I need to add an authorization value to the request header when navigating to a site but am unable to find a way to do it. Since this is control is relatively new and my first time using it, I could also be completely missing the method that actually does this.

The only information I can find so far is found in the c++ documentation: ICoreWebView2HttpRequestHeaders

It specifically says

Used to inspect the HTTP request on WebResourceRequested event and NavigationStarting event. Note, you can modify the HTTP request headers from a WebResourceRequested event, but not from a NavigationStarting event.

This event is available in .NET and I am able to catch it and see the request headers but they don't seem editable or at least I am trying to edit them incorrectly. After I try to edit the header, the authorization property is still null and is not passed through with the request.

private void CoreWebView2_WebResourceRequested(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebResourceRequestedEventArgs e)
{
    var authHeaderValue = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "the_token_value");
    e.Request.Headers.Authorization = authHeaderValue;
}

What is the correct way, if there is a way, to set this value as you cannot seem to modify the eventargs directly. It's also very likely I could be using this event wrong.

Any assistance is appreciated.


Solution

  • This is a known bug on WebView2 currently being worked on: https://github.com/MicrosoftEdge/WebViewFeedback/issues/259

    If you find more bugs like this in the future feel free to open issues on the feedback repo: https://github.com/MicrosoftEdge/WebViewFeedback/issues

    Thanks!