如何使用 webview2 发布数据

问题描述

我需要一个登录请求。我在 WPF 中使用 webview2 包并使用它。

我的代码是这样的:

  HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,new Uri("Sample_url"));
        request.Content = new FormUrlEncodedContent(new[] {
            new keyvaluePair<string,string>("email",email),new keyvaluePair<string,string>("password","123"),});
     // webview2 does not contain a defenition for 'NavigateWithHttpRequestMessage'
     browser.NavigateWithHttpRequestMessage();

我想做的是先登录用户,然后向他展示视图。

解决方法

使用 WebView2 version 1.0.790-prelease(可能更早),您可以使用 CoreWebView2WebResourceRequest 创建一个 webView.CoreWebView2.Environment.CreateWebResourceRequest() 对象。 然后可以将其传递给 NavigateWithWebResourceRequest

例如:

var request = webView.CoreWebView2.Environment.CreateWebResourceRequest(navigateData.Url,"POST",postData,"Content-Type: application/x-www-form-urlencoded");
webView.CoreWebView2.NavigateWithWebResourceRequest(request);
,

好吧,当我给你那个链接时,这并不像我想象的那么容易。

首先,CoreWebView2.NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest) 仅包含在 pre-releaseWebView2 版本中。

其次,CoreWebView2WebResourceRequest 没有公共构造函数,因此您实际上无法使用它(在 WebResourceRequested 事件处理程序之外)。

这显然是一个“预发布”的东西,还没有准备好使用。

那么,你在做什么?

嗯,我建议,你用这个方法,我已经用了一段时间了:

1. Navigate to the login page,using the `Source` property.
2. Get the names of the `input` elements for 'email' and 'passwords'.
3. Construct some javascript to set the values of those 2 elements and perform a `click` on the button,that posts the form.

那应该让您登录。