c# - 获取 api 响应时出错对象引用未设置为对象的实例

标签 c# asp.net-mvc asp.net-mvc-5

问题

一旦我收到响应并尝试存储它,该对象将为空,并且我收到此错误:

未将对象引用设置为对象的实例。

代码

var result = await response.Content.ReadAsStringAsync();
var jsonResult = JsonConvert.DeserializeObject<dynamic>(result);
var value = (JToken)jsonResult.value;

图片

enter image description here

enter image description here

最佳答案

在尝试 (JToken)jsonResult.value 之前尝试检查 jsonResult != null

[编辑]

你可以使用 var value = (JToken)jsonResult;末尾不需要 .value。

        var result = "{ \"id\": \"/apis/574c167dcd7c3216c8c633b3\", \"name\": \"Servicedesk and Operations\", \"description\": \"Servicedesk and Operations Internal API\", \"serviceUrl\": \"dev-endpoint.com\", \"path\": \"test\", \"protocols\": [ \"http\", \"https\" ], \"authenticationSettings\": { \"oAuth2\": null, \"openid\": null }, \"subscriptionKeyParameterNames\": { \"header\": \"Ocp-Apim-Subscription-Key\", \"query\": \"subscription-key\" } }";
        var jsonResult = JsonConvert.DeserializeObject<dynamic>(result);
        var value = (JToken)jsonResult;
        var id = value["id"].ToString();

[额外编辑]

或者你可以选择

         var id2 = jsonResult.id;

因为你在那里有活力

关于c# - 获取 api 响应时出错对象引用未设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873412/

相关文章:

asp.net - 安装 Ninject.MVC5 后出现 FileLoadException

c# - 使用 WEB API HttpClient 使用外部 API 然后以 Angular 显示反序列化结果是否可以接受?

c# - 找到多个与 URL 匹配的 Controller 类型。 ASP.Net MVC

asp.net-mvc - 模型绑定(bind)下拉选择值

asp.net-mvc - 从 Controller 获取基本 URL 的最佳方法是什么

asp.net-mvc - ASP.NET身份与简单成员资格的利与弊?

c# - 为什么我得到 "could not find file '\[文件名 ]'"?

c# - 为什么在枚举内声明位域的组合会产生与在枚举外声明不同的结果?

c# - 是否有内置方法来序列化数组配置值?

c# - 单元测试 ASP.NET MVC5 应用程序