Search code examples
c#.netwpfwinformswebview2

set Webview2 header or cookie


I want to set customized header for all requests that Webview2 makes. Please help. Basically I want to load website in webview itself so it is needed that I receive my header on all requests.

MainWindow.xaml.cs

using Microsoft.Web.WebView2.Core;
using System;
using System.Windows;

namespace O2C
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void webView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            webView.CoreWebView2.Settings.UserAgent = "O2C-Web";
            webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
            webView.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
        }

        private void WebView_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
        {
            e.RequestHeaders.SetHeader("X-Authorization", "My Auth");
        }
    }
}
e.RequestHeaders.SetHeader("X-Authorization", "My Auth");

I have found the correct event which will work for the requirement but I don't know how to call that event from xaml file or from .cs file. Following docs say thaat this event will work for the requirement.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.webresourcerequested?view=webview2-dotnet-1.0.864.35

BUT how to hook that event and from where I don't know.


Solution

  • I Solved it after looking at many places.

    If you want the WebResourceRequested Event then you must register the Filter that will intercept all requests for all resources. Then and then it will work or called.

    I am posting whole code here:

    private void webView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
    {
          //Following line is MUST if you want to use WebResourceRequested Event
          webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
          webView.CoreWebView2.Settings.UserAgent = "MY-AGENT";
          webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
          webView.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
          webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
    }
    
    private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
    {
          e.Request.Headers.SetHeader("X-Authorization", "My Auth");
    }
    

    Thanks all for support and ideas. Hope this solution helps.