繁体   English   中英

如何在 WebView2 中获取服务器响应代码

[英]How do I get server response code in WebView2

我正在尝试使用 WebView2 并获取服务器响应代码。 但是 CoreWebView2WebResourceRequestedEventArgs.Response 总是 null 出于某种原因:

    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");
        }
    }

如何获取响应码?

我认为e.Response将始终是null因为WebResourceRequested事件是在发送请求之前触发的。 您应该在事件处理程序中创建响应。 那不是你想要的。

所以你会怎么做? 好吧, WebView2的新预发布版本可能具有您想要的 - WebResourceResponseReceived事件。 当您收到来自服务器的响应并且此处e.Response将可用时,这会触发。

要使用它:

  1. 安装/更新Microsoft.WebView2预发布版本(最新)。
  2. 安装 Microsoft Edge 的Canary版本。
  3. 卸载WebView2 运行时 - 否则仍将使用它。

现在您可以使用如下代码(注意新的事件名称):

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);
            }
        }
    }
}

注意如果header不存在, e.Response.Headers.GetHeader会抛出异常,所以先检查一下。

看起来昨天(1.0.1293.44)发布的 WV2 SDK 添加了一个新接口,它将为我们提供我们需要的东西:

https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2navigationcompletedeventargs2?view=webview2-1.0.1293.44

interface ICoreWebView2NavigationCompletedEventArgs2 : 
public ICoreWebView2NavigationCompletedEventArgs

get_HttpStatusCode  The HTTP status code of the navigation if it involved an HTTP request.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM