我有什么
此代码调用我的 API:
HttpResponseMessage response = await Http.GetAsync("https://localhost:7094/api/MyResource/94d0e5ca-2be7-42f7-94dc-13955c11595c");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: {responseBody}");
var payload = JsonSerializer.Deserialize<MyClass>(responseBody);
var json = JsonSerializer.Serialize(payload);
Console.WriteLine($"PAYLOAD: {json}");
此代码是从 NET8 Blazor WASM 客户端中的
OnInitializedAsync
调用的。
我得到的回应
responseBody 的第一个 WriteLine 返回:
{
"creationOptions": 0,
"id": 226,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"isFaulted": false,
"result": {
"content": {
<Actual content>
},
"links": {
<my hateoas links>
}
},
"status": 5
}
这是正确的。
失败的原因是什么
MyClass 的反序列化似乎没有正确发生,因为第二个写入行返回以下内容:
PAYLOAD: null
这并不奇怪,因为responseBody 添加了http get 结果。我需要沿着 json 树走一次。
我做不到:
var payload = JsonSerializer.Deserialize<MyClass>(responseBody.result);
因为responseBody是字符串类型,如上所示。
我也试过
使用
var payload = Http.GetFromJsonAsync<Payload<FabricageSoort>>("https://localhost:7094/api/MyResource/94d0e5ca-2be7-42f7-94dc-13955c11595c");
但这会返回:
{ "content": null, "links": null }
我怀疑这是一个时序问题(当我写入时数据尚未准备好)。
从 json responseBody 获取实际负载的最佳方法是什么?
你可以尝试:
{
HttpResponseMessage response = await Http.GetAsync("API");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"RESPONSE: {responseBody}");
var fullResponse = JsonSerializer.Deserialize<MyClass>(responseBody);
var payload = fullResponse?.result?.content;
if (payload != null)
{
var json = JsonSerializer.Serialize(payload);
Console.WriteLine($"PAYLOAD: {json}");
}
else
{`enter code here`
Console.WriteLine("Payload is null or not found in the response structure.");
}
}