【发布时间】:2021-12-02 05:41:07
【问题描述】:
我在 MVC Core 应用的 Controller 中调用 API,如下所示:
HttpContent httpContent = new StringContent(string.Empty, Encoding.UTF8, "text/plain");
HttpResponseMessage response = await client.PostAsync("api/users", httpContent);
if (response.IsSuccessStatusCode) {
User userJson = await response.Content.ReadFromJsonAsync<User>();
string responseContent = await response.Content.ReadAsStringAsync();
responseContent 的值为:
"{
\"actionName\":\"GetUser\",
\"routeValues\":{\"id\":\"30131055-9ff0-472f-a147-69e76f7aac77\"},
\"value\":{\"uid\":\"a36065bd-9d88-4ea3-f04d-08d98cfa8b83\",
\"email\":\"example@example.org\",
\"active\":true,\"created\":\"2021-10-12T19:49:16.0054897Z\",
\"updated\":\"2021-10-12T19:49:16.0054899Z\"},\"formatters\":[],
\"contentTypes\":[],
\"statusCode\":201
}"
我没想到这种类型的格式化内容,我期待的是 JSON,但我可以在“值”部分看到我的用户对象的值。
uid、email、active、created 和 updated 的 My User 对象属性都是具有 get/set 方法的公共属性。
所以我可以看到我的数据在那里,但是当我尝试反序列化对 User 对象的响应时,我只看到实例化后的默认值。
我觉得我错过了一些简单的东西。
【问题讨论】:
-
简单地说:读取两次响应内容是错误的,并且可能会失败,具体取决于您使用的 API 的工作方式。如果你需要这样做,首先读取为字符串,然后从已经在内存中的字符串反序列化
标签: c# json asp.net-core-mvc asp.net-core-webapi dotnet-httpclient