Home > Enterprise >  c# Any sample code to POST xml payload using Webview2?
c# Any sample code to POST xml payload using Webview2?

Time:06-11

I'm using winform with Webview2 and trying to access a website using POST xml payload. I am very new to Webview2 and can't seem to go anywhere with it. I can browse through Webview2 like normal, but cannot seem to find a way to post the xml payload. Any samples would be greatly appreciated!! I have tried the following, but no luck.

        using (var stream = CreateStream(data))
        {
            webView21.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);

            CoreWebView2WebResourceRequest webResourceRequest = webView21.CoreWebView2.Environment.CreateWebResourceRequest(uri, "POST", stream, "Content-Type: application/x-www-form-urlencoded");
            webView21.CoreWebView2.NavigateWithWebResourceRequest(webResourceRequest);
        }
    }
    public static Stream CreateStream(string s)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }

CodePudding user response:

Remove the using statement and your code will work (also the AddWebResourceRequestedFilter is unnecessary). The CoreWebView2.Navigate* methods start a navigation but it is not complete until the various navigation events are raised. Your stream is required for the navigation which will continue on after the NavigateWithWebResourceRequest method completes.

        var stream = CreateStream(data);

        CoreWebView2WebResourceRequest webResourceRequest = webView21.CoreWebView2.Environment.CreateWebResourceRequest(uri, "POST", stream, "Content-Type: application/x-www-form-urlencoded");
        webView21.CoreWebView2.NavigateWithWebResourceRequest(webResourceRequest);
    }
    public static Stream CreateStream(string s)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }

WebView2 should be done with the stream once the CoreWebView2.ContentLoading event has been raised at which point the stream can be disposed.

  • Related