Search code examples
c#wpfwebview2

How to post data with webview2


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.


Solution

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