我正在尝试将数据从API获取到我的剃须刀页面以使用此数据。我已经通过异步函数成功地从API中获取了数据,并尝试将其发送到razor页面,但是即使通过传递时数据在那里,它也不会通过return view调用传递到razor页面。
我在这里设置了一个断点,所有数据都在对象return View(standingsParent);
中,但是在传递到页面@Model.ToString();
之后是NullReferenceException
我曾考虑删除异步功能,但由于等待API响应,这会减慢我的网站的速度。我没有尝试过其他值得一提的事情,没有运气就对此进行了彻底的研究。
这是我返回视图的地方
StandingsParent standingsParent;
private async Task LoadTable()
{
standingsParent = await Football.LoadFootballTable();
}
public async Task<ViewResult> Table()
{
await LoadTable();
return View(standingsParent);
}
加载表功能
public static async Task<StandingsParent> LoadFootballTable(string tableId = "PL")
{
string url = $"https://api.football-data.org/v2/competitions/{tableId}/standings?standingType=TOTAL";
HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url);
using (response)
{
if (response.IsSuccessStatusCode)
{
//Region region = await response.Content.ReadAsAsync<Region>();
StandingsParent standings = await response.Content.ReadAsAsync<StandingsParent>();
return standings;
}
else
{
throw new System.Exception(response.ReasonPhrase);
}
}
}
APIClient
public static HttpClient ApiClient { get; set; }
public static void InitialiseClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Add("X-Auth-Token", "MyToken");
}
我的观点
@page
@using CoreWebApp.Models.Football
@model StandingsParent
<h1>Table</h1>
<p>
@Model.ToString();
</p>
我希望有一些输出只是为了表明数据在那里可以操纵,但是我现在所得到的只是
NullReferenceException
:
对象引用未设置为对象的实例。