0

I am trying to call a PHP file from my c# code. This is my c# code.

  User user = new User();
                user.firstname = "aaaa";
                user.secondname = "aaaaaaaaaaa";
                user.email = "aaa";
                user.phonenumber = "aaa";

                string json = JsonConvert.SerializeObject(user);
                HttpWebRequest request = WebRequest.Create("http://localhost") as HttpWebRequest;
                request.ContentType = "application/json";
                //request.Accept = "application/json, text/javascript, */*";
                request.Method = "POST";
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(json);
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream stream = response.GetResponseStream() ;

                string json1 = "";

                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        json1 += reader.ReadLine();
                    }
                }

                MessageBox.Show(json1);

My problem is that the c# method is not sending my object and my php code is

<?php    
     echo  json_encode($_POST);
?>

please help

2

2 Answers 2

1

$_POST doesn't understand json as per my comment pointing to the solution elsewhere on SO (Google makes life easier)

Here is the recommended code to use:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is your C# is sending raw POST data and the PHP $_POST array only works with URL encoded key/value pairs.

On the PHP side, retrieve the raw POST data, bypassing the $_POST array. Also it makes no sense to JSON encode the data on the PHP side, because it is already JSON. Use json_decode() for the reverse operation.

echo file_get_contents("php://input");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.