How do I get server response code in WebView2

Viewed 2465

I am trying to use WebView2 and get the server response code. However CoreWebView2WebResourceRequestedEventArgs.Response is always null for some reason:

    webView.CoreWebView2Ready += CoreWebView2Ready;        

    private void CoreWebView2Ready(object sender, EventArgs e)
    {
        webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
        webView.CoreWebView2.WebResourceRequested += WebResourceRequested;
    }

    private void WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
    {
        /* e.Response is always null for some reason */
        if (e.Response != null)
        {
            int statusCode = e.Response.StatusCode;
            string header = e.Response.Headers.GetHeader("myheader");
        }
    }

How do I get the response code?

2 Answers

I think e.Response will always be null because the WebResourceRequested event is triggered before the request is sent. You're supposed to create a response in the eventhandler. That is not what you want.

So what do you do? Well, the new pre-release version of WebView2 might have, what you want - a WebResourceResponseReceived event. This is triggered when you receive a response from the server and here the e.Response will be available.

To use it:

  1. Install/update Microsoft.WebView2 pre-release version (latest).
  2. Install the Canary build of Microsoft Edge.
  3. Uninstall the WebView2 Runtime - otherwise that will still be used.

Now you can use code like below (note the new event names):

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

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            webView21.CoreWebView2.WebResourceResponseReceived += CoreWebView2_WebResourceResponseReceived;
        }

        private void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
        {
            if (e.Response != null && e.Response.Headers.Contains("date"))
            {
                int statusCode = e.Response.StatusCode;
                string header = e.Response.Headers.GetHeader("date");
                MessageBox.Show(header);
            }
        }
    }
}

Note that e.Response.Headers.GetHeader will throw an exception if the header doesn't exist, so check it first.

Related