PostAsJsonAsync POST 变量未到达 Flight PHP REST 服务器

问题描述 投票:0回答:2

我设置了 Flight PHP REST 服务器。 在第一个端点,它需要 POST 数据,并根据 POST 数据之一从数据库检索一些数据并将其作为 JSON 返回。

当我在 Chrome 中使用 Postman REST 扩展时,我看到了正确的结果。但是当我使用 C# 应用程序进行调用时,返回的 json 为 null,因为 $_POST 似乎为空。

这是我的航班index.php:

Flight::route('POST /getText', function(){  
  // Create a new report class:
  $reportText = new ReportText;
  $theText = $reportText->ParsePost($_POST);
  if ($theText == null)
  {
    echo null;
  }
  else
  {
    echo json_encode($theText);
  }        
});

这是我的 ParsePost:

public function ParsePost($PostDictionary)
{
    $textArray = null;
    foreach ($PostDictionary as $key => $value)
    {
        if (!empty($value))
        {
            list($tmp, $id) = explode("_", $key);
            $text = $this->geFooWithText($id);
            $textArray[$key] = "bar";
        }
    }

    return $textArray;
}

这是我的 C# 部分:

private static async Task RunAsyncPost(string requestUri)
{
    using (var client = new HttpClient())
    {
        // Send HTTP requests
        client.BaseAddress = new Uri("myUrl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // HTTP POST
            var response = await client.PostAsJsonAsync(requestUri, new { question_8 = "foo", question_9 = "bar" });
            response.EnsureSuccessStatusCode(); // Throw if not a success code.
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                if (string.IsNullOrEmpty(json))
                {
                    throw new ArgumentNullException("json", @"Response from the server is null");    
                }

                var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                foreach (var kvp in dictionary)
                {
                    Debug.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
                }
            }
        }
        catch (HttpRequestException e)
        {
            // Handle exception.
            Debug.WriteLine(e.ToString());
            throw;
        }
    }
}

这是邮递员的回复:

{
  "question_8": "foo",
  "question_9": "bar"
}

我在使用 C# 的通话中似乎遗漏了一些内容。

[更新]

在这篇文章中(无法对通过 C# 传递 json 的 REST 服务执行 HTTP POST )似乎出现了同样的问题。 建议使用 Fiddler。

使用 Postman 和 x-www-form-urlencoded:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 29
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

question_8=foo&question_9=bar

使用 Postman 和表单数据:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 244
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvb4wmaP4KooT6TFu
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_8"

foo
------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_9"

bar
------WebKitFormBoundaryvb4wmaP4KooT6TFu--

使用我的 C# 应用程序:

POST http://myHost/api/getText/ HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: myHost
Content-Length: 50
Expect: 100-continue
Connection: Keep-Alive

{"question_8":"foo","question_9":"bar"}

C# 应用程序以不同的方式清楚地发送它。

c# json rest dotnet-httpclient flightphp
2个回答
1
投票

我发现问题了。

因为我使用

client.PostAsJsonAsync()
,POST 数据以 json 形式发送,正如您在 Fiddler 中看到的那样。

PHP 不期望 POST 数据为 json 格式。 要读取该数据,我需要在 PHP 文件中使用

$data = file_get_contents('php://input');

现在我有了我的钥匙和价值观,我可以继续吗?看起来 PHP 需要一个 $_JSON 变量;)


0
投票

为了防止其他人偶然发现这一点,我在 index.php 文件的顶部创建了这个小循环,该循环从 C# 进行 POST 调用。 它从

php://input
中的字符串恢复 $_POST 变量,但前提是 $_POST 为空

if (count($_POST) == 0) {
    try {
        $copy = json_decode(file_get_contents('php://input'), true);
        foreach($copy as $k => $v) 
            $_POST[$k] = $v;
    } catch (exception $e) {
        // do nothing
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.