如何使用Webview2发布数据

6
我需要一个登录时的 POST 请求。我正在使用 WPF 中的 webview2 包,并使用以下代码:
```html

My code is this:

```
  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();

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

2个回答

9

使用 WebView2 版本 1.0.790-prelease(可能甚至更早版本),您可以使用 webView.CoreWebView2.Environment.CreateWebResourceRequest() 创建一个 CoreWebView2WebResourceRequest 对象。

然后将其传递给 NavigateWithWebResourceRequest

比如:

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

如果您将postData设置为null,则浏览器既不会实际导航,也不会抛出异常。 - Willster419

1
好的,当我给你那个链接时,这并不像我想象的那么容易。
首先,CoreWebView2.NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest) 只包含在 pre-release 版本的 WebView2 中。
其次,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.

那应该会让你登录。

实际上,我已经得到了一个GET路由并传递了我的API令牌,所以现在我已经登录了,但还是谢谢。我可能会构建一些JavaScript。 - Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接