我有一个调用 IEXTrading api 的应用程序。调用本身返回数据,但是当我想将其加载到视图模型中以呈现它时,它返回一条错误消息“无法反序列化当前 JSON 对象”我创建了一个单独的视图模型,数据应加载到其中。
我的控制器
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://cloud.iexapis.com/");
HttpResponseMessage response = client.GetAsync($"stable/stock/aapl/quote?filter=symbol,companyName,volume,latestSource,latestPrice,latestTime&token=MY_KEY").Result;
var resultList = response.Content.ReadAsAsync<List<GetQuoteAPIViewModel>>().GetAwaiter().GetResult();
}
return View(resultList);
}
我的视图模型
namespace WebApplication1.Models.ViewModels
{
public class GetQuoteAPIViewModel
{
public IList<ApiQuote> apiQuote { get; set; }
}
}
我的模型:
public class ApiQuote
{
public string symbol { get; set; }
public string companyName { get; set; }
public string LatestTime { get; set; }
public string latestSource { get; set; }
public int iexVolume { get; set; }
public decimal latestPrice { get; set; }
public System.Net.HttpStatusCode IsSuccessStatusCode { get; set; }
}
}
我的观点:
@model WebApplication1.Models.ViewModels.GetQuoteAPIViewModel
@{
ViewData["Title"] = "Home Page";
}
<div>
@foreach(var quote in Model)
{
@quote.latestPrice
@quote.LatestTime
@($"{quote.symbol}, {quote.companyName}")
@quote.latestSource
}
</div>
显然,我错过了转换为特定类型之类的东西。但是,如果我直接使用模型然后使用 varresultList = response.Content.ReadAsAsync<GetQuoteAPIViewModel>().GetAwaiter().GetResult();数据会加载到我的视图中。那么问题似乎是我不能使用索引或枚举,因为它没有枚举器。解决此问题的典型 .net 核心 MVC 方法是什么,包括视图模型等?