Send POST data to URL with CefSharp C#

jLynx picture jLynx · Feb 24, 2017 · Viewed 10.2k times · Source

Im trying to work out how to send post data directly to a url with cefsharp. Here is an example of what I want to send:

var values = new Dictionary<string, string>
{
     { "thing1", "hello" },
     { "thing2", "world" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(values);

Which will create thing1=hello&thing2=world I want to send this POST data to the url http://example.com/mydata.php using the existing browser with cefsharp.

From what I can see

browser.Load("http://example.com/mydata.php");

Has no way to attach POST data, is there a way I can do this?

Basically I need to keep the same cookies that the browser already has, so if there is another way to do this for example using HttpWebRequest with the cefsharp ChromiumWebBrowser cookies then syncing them again after that request, that would also work, but i'm not sure if that is possible.

Answer

jwezorek picture jwezorek · May 25, 2017

You can issue a POST using CefSharp via the LoadRequest method of the IFrame interface.

For example, you can make an extension method that implements the equivalent of Microsoft's System.Windows.Forms.WebBrowser.Navigate(..., byte[] postData, string additionalHeaders) with something like

public 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);
    }