How to post data with webview2

Viewed 5116

I need a post request for a login. I'm using the webview2 package in WPF and using it.

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

what i want to do is login the user in first then show him the view.

2 Answers

Using WebView2 version 1.0.790-prelease (probably even earlier), you can create a CoreWebView2WebResourceRequest object using webView.CoreWebView2.Environment.CreateWebResourceRequest(). This can then be passed to NavigateWithWebResourceRequest.

So, for example:

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

Ok, this is not as easy as I thought, when I gave you that link.

First, CoreWebView2.NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest) is only included in the pre-release version of WebView2.

Second, CoreWebView2WebResourceRequest does not have a public constructor, so you can't actually use it (outside the WebResourceRequested event handler).

This is clearly a 'pre-release' thing that isn't ready to be used yet.

So, what do you do?

Well, I suggest, you use the method, I have used for some time:

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.

That should log you in.

Related