How to POST NULL value C#

739 Views Asked by At

I need to POST data from C# WinForms application into PHP page. I'm using WebClient with sample code below:

using (WebClient client = new WebClient())
{
    NameValueCollection values = new NameValueCollection();
    values.Add("menu_parent", null);

    string URL = "http://192.168.20.152/test.php";
    byte[] response = client.UploadValues(URL, values);

    string responseString = Encoding.Default.GetString(response);

    MessageBox.Show(responseString);
}

On the PHP side, I'm doing simple IF condition to test whether the menu_parent is NULL or not with this very simplified code:

<?php
$parent = $_POST['menu_parent'];

if ($parent === null)
    echo "menu_parent is null";
else
    echo "menu_parent is: <".$parent.">"; // This prints out.

if (is_null($parent))
    echo "menu_parent is also null";
else
    echo "menu_parent is also: <".$parent.">" // This also prints out.

if ($parent === "")
    echo "menu_parent is empty string"; // This also prints out.
else
    echo "menu_parent is not empty";
?>

The problem is the NULL value of menu_parent is converted into empty string in the PHP page. I've checked the MSDN page about WebClient.UploadValues method and also NameValueCollection class. The page said that NULL value are accepted. How to POST null value? Is NULL value is unacceptable in this case?

2

There are 2 best solutions below

1
apokryfos On BEST ANSWER

The HTTP protocol is a textual protocol and therefore you can't really send a "null" value.

Assuming you're using the JSON.net library (though there's probably equivalent ways to do this built-in).

using (WebClient client = new WebClient())
{
    var values = new Dictionary<string,object> { { "menu_parent",null } }; 
    var parameterJson = JsonConvert.SerializeObject(values);
    client.Headers.Add("Content-Type", "application/json"); 

    string URL = "http://192.168.20.152/test.php";
    byte[] response = client.UploadData(URL, Encoding.UTF8.GetBytes(parameterJson));

    string responseString = Encoding.Default.GetString(response);

    MessageBox.Show(responseString);
}

Then in PHP you can do:

$data = json_decode(file_get_contents('php://input'));
if ($data->menu_parent === null) {
   //should work
}
0
nomad culture On

I always use a data model and send it as object in C# after deserialization-serialization with JsonConvert class. Then in PHP, I always get it as object and convert it to related model again. So there is no NULL key-value loss. But "NameValueCollection" has equal data model in PHP(?), I don't know.