简体   繁体   中英

CefSharp make a POST web api call Win Forms c#

I want to use CefSharp to make a POST web api call in Win Forms c#.

I have Basic Authentication for my POST request. But if I run the code I get the error on line IFrame frame = browser.GetMainFrame(); :

Browser is not yet initialized. Use the IsBrowserInitializedChanged event and check the IsBrowserInitialized property to determine when the browser has been intialized.

Is there a way to resolve the same?

Following is my code:

public partial class Form1 : Form
{

    ChromiumWebBrowser browser = null;
    public Form1()
    {
        InitializeComponent();

        Cef.Initialize(new CefSettings());
        browser = new ChromiumWebBrowser("http://ctstest.azurewebsites.net/api/default");
        this.Controls.Add(browser);
        browser.Dock = DockStyle.Fill;

        PostTest.Navigate(browser, "http://ctstest.azurewebsites.net/api/default", null, "application/json");

    }
}

public static class PostTest
    {
    public static void Navigate(this IWebBrowser browser, string url, byte[] postDataBytes, string contentType)
    {
        IFrame frame = browser.GetMainFrame();
        IRequest request = frame.CreateRequest();

        request.Url = url;
        request.Method = "POST";

        request.InitializePostData();
        var element = request.PostData.CreatePostDataElement();
        element.Bytes = postDataBytes;
        request.PostData.AddElement(element);

        NameValueCollection headers = new NameValueCollection();
        headers.Add("Content-Type", contentType);
        request.Headers = headers;

        frame.LoadRequest(request);

        frame.GetTextAsync().ContinueWith(taskHtml =>
        {
            var html = taskHtml.Result;
            System.Windows.Forms.MessageBox.Show(html);
        });

        string script = string.Format("document.documentElement.outerHTML;");
        frame.EvaluateScriptAsync(script).ContinueWith(x =>
        {
            var response = x.Result;

            if (response.Success && response.Result != null)
            {
                var fullhtml = response.Result;
                System.Windows.Forms.MessageBox.Show(fullhtml.ToString());
            }
        });
    }

}
}

Thanks.

Well like the error message is telling you, you should check if the browser is already initialized.

I don't know the implementation of the class ChromiumWebBrowser but I would try to first navigate to the desired url

browser.navigate(yourUrl);

and maybe check if the browser has already navigated to your url by subscribing to the event IsBrowserInitialized before calling browser.GetMainFrame() (like amaitland mentioned)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM