PostAsJsonAsync,结果未知
本文关键字:未知 结果 PostAsJsonAsync | 更新日期: 2023-09-27 18:30:41
我正在用HttpClient和C#迈出第一步。我正在尝试发布到 PHP REST 服务器并使用其返回的 JSON。当我发布到返回"Hello World!"的终点时,一切都很好。但是当它返回时{ "key1": "test1", "key2": "test3"}我无法解析它。
这是我的代码:
private static async Task RunAsyncPost(string requestUri, object postValues)
{
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, postValues);
response.EnsureSuccessStatusCode(); // Throw if not a success code.
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
Debug.WriteLine(result);
}
}
catch (HttpRequestException e)
{
// Handle exception.
Debug.WriteLine(e.ToString());
throw;
}
}
}
问题似乎出在这条线上:
var result = await response.Content.ReadAsStringAsync();
很可能我需要将其更改为 ReadAsAsync<>,但我尝试了许多选项,但结果仍然为空或出现运行时错误。
我感兴趣的终点将返回各种长度的数组,因此我不能使用强类型类。
[更新]
我正在使用 Chrome 中的 Postman Rest 扩展将两个表单-数据键-值对发送到同一个 URL,并且 Postman 返回了正确的值。所以我假设我的PHP REST服务器没问题。
这是我的调用方法:
public void TestPost()
{
RunAsyncPost("api/postTest/", new { question_8 = "foo", question_9 = "bar" }).Wait();
}
如果您的返回值长度为 N(仅在运行时已知),则您有两种选择(我将使用 Json.NET 进行反序列化):
- 将
返回的 json 解析为
dynamic
对象。如果您在编译时知道密钥,请使用以下命令:var json = await response.Content.ReadAsStringAsync(); // Deserialize to a dynamic object var dynamicJson = JsonConvert.DeserializeObject<dynamic>(json); // Access keys as if they were members of a strongly typed class. // Binding will only happen at run-time. Console.WriteLine(dynamicJson.key1); Console.WriteLine(dynamicJson.key2);
将返回的json解析为
Dictionary<TKey, TValue>
,在这种情况下它将是一个Dictionary<string, string>
:var json = await response.Content.ReadAsStringAsync(); var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); foreach (KeyValuePair<string, string> kvp in dictionary) { Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value); }
作为旁注,这样做:
RunAsyncPost("api/postTest/", new { question_8 = "foo", question_9 = "bar" }).Wait();
是async-await
中的反模式。不应通过异步方法公开同步包装器。相反,请调用同步 API,例如 WebClient
提供的同步 API。