Search code examples
c#asp.nethttpwebrequest

What is the equivalent way to set post parameters in .net?


I have to integrate with a third party API. To use the service, I have to "POST" to a specific url with certain parameters.

The example code provided by the service is in php and is as follows

$data = array('From' => '0999999', 'To' => '08888888'); 
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  <--- Ignore SSL warnings
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

I am trying to use the WebRequest class to achieve the same in .net. However, I am a bit confused about how to set the post parameter data. I figured $data above is nothing but a Dictionary. So I created a equivalent dictionary. However, how do I set the post parameters with the dictionary values?

In http://msdn.microsoft.com/en-us/library/debx8sh9.aspx, they have serialized a string to a byte array and then set is as the post parameter in the dataStream. How do I do the same for a Dictionary?

Or is my approach incorrect? Is there a better way to do this?


Solution

  • Generally, WebClient.UploadValues is going to be the easiest approach here; see MSDN for a full example. Note, however, that this only covers CURLOPT_POSTFIELDS and CURLOPT_POST. Fail on error is automatic and implicit, and the response is already included as a byte[].

    i.e.

    using(var client = new WebClient()) {
        var data = new NameValueCollection();
        data.Add("From", "0999999");
        data.Add("To", "08888888");
        var result = client.UploadValues(url, data);
    }
    

    note POST is implicit here; if you need a different http method, use the overload:

    var result = client.UploadValues(url, "PUT", data); // for example