9

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.

jLynx
  • 1,111
  • 3
  • 20
  • 36

1 Answers1

12

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);
    }
jwezorek
  • 8,592
  • 1
  • 29
  • 46
  • It's not necessary to inherit from ChromiumWebBrowser. You could easily make this an extension method. Converting your data to a string is actually going to then use the default encoder to convert it back to a byte array, your using https://github.com/cefsharp/CefSharp/blob/cd934267c65f494ceb9ee75995cd2a1ca0954543/CefSharp/PostDataExtensions.cs#L128 when you should set the data directly. – amaitland May 25 '17 at 21:41
  • How do I set the data directly? – jwezorek May 25 '17 at 22:22
  • like this: request.InitializePostData(); var postData = request.PostData; var element = postData.CreatePostDataElement(); element.Bytes = postDataBytes; request.PostData.AddElement(element); ? – jwezorek May 25 '17 at 22:28