如何从类中访问 GET 方法的结果?

问题描述

我有一个 get 方法。此方法调用来自不同项目的端点并获取客户信息。我想在另一个班级中使用这个客户的信息。但我不知道如何访问它。

将我通过该方法获得的信息写入数据库然后从那里读取它是一个选项,但是客户数量可能很高并且客户信息中可能有更新。这就是为什么我必须在需要的时候打电话。

我的 GetCustomerinformation(customerIdList) 方法返回:return Ok(customerInfoList);

当我想在另一个班级获得 customerInfoList 时,我尝试了类似的方法

var customerList = _customerInfoController.GetCustomerinformation(customerIdList).Result;

它返回一个 ActionResult,我怎样才能得到 customerInfoList 作为 List

解决方法

假设

var customerList =_customerInfoController.GetCustomerInformation(customerIdList)

是一个外部 Web API 调用.. customerList 的类型将是 HttpResponseMessage。因此,我们需要将该数据转换为字符串,然后转换为特定对象,然后您才能访问该列表。

var response = customerList .Content.ReadAsStringAsync().Result;
var data= JsonConvert.DeserializeObject<List<YourSpecificObject>>(response);

您可能需要创建一个类,其中客户列表的所有指定属性为 YourSpecificObject..

,

首先在你要使用的项目中添加API所在的项目引用(如下图)

enter image description here

那么你的新类(在其他项目中)可以这样实现。

@using APIProject;
public IList<YourSpecificObject> customerList { get; set; }
public async Task<IActionResult> OnPost(customerIdList)
{
  customerList =_customerInfoController.GetCustomerInformation(customerIdList)
}

希望这会有所帮助。谢谢。