6

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.

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
Ali
  • 615
  • 10
  • 16
  • See this: https://learn.microsoft.com/da-dk/dotnet/api/microsoft.web.webview2.core.corewebview2.navigatewithwebresourcerequest?view=WebView2-dotnet-1.0.721-prerelease&viewFallbackFrom=webview2-dotnet-1.0.664.37#Microsoft_Web_WebView2_Core_CoreWebView2_NavigateWithWebResourceRequest_Microsoft_Web_WebView2_Core_CoreWebView2WebResourceRequest_ – Poul Bak Dec 20 '20 at 17:03
  • can explain to me in a simple example post request with Browser as webview2 declared in xaml ? thank you – Ali Dec 20 '20 at 21:05

2 Answers2

9

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);
Jack Miller
  • 6,843
  • 3
  • 48
  • 66
1

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.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
  • actually i got a get route and passed my api-token so im login with that now but thanks. i might construct some javascript. – Ali Dec 23 '20 at 21:27