借用https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client中的 Get 方法,我编写了以下内容. 虽然是 C# 的新手,但我认为 await 将完成 API 调用然后继续,但发生的情况是该行执行然后退出该方法而不运行另一行代码(if 语句,返回)。我可能还假设了其他事情,这导致我陷入了这种困境。
代码应该是什么才能始终如一地从 API 调用中获得响应并反序列化 Json,以便我可以检索我实际需要的 2 位数据?
对我的代码的任何其他建议改进也非常感谢。
方法调用:
var ReturnedData = GetProductAsync(companyCode);
方法:
//API Call method - https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
static HttpClient client = new HttpClient();
static async Task<ReturnedAPIdata> GetProductAsync(string CoCode)
{
// TODO - This key will need to be taken out of the code and put in a config file or something
string DavesKey = "abc123";
string path = "http://api.marketstack.com/v1/eod?access_key=" + DavesKey + "&symbols=" + CoCode + ".XASX&sort=DESC&limit=1&offset=0";
ReturnedAPIdata ThatAPIdata = null;
HttpResponseMessage response = await client.GetAsync(path);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
// If we have an API response, deserialise the Json data... somehow
//ThatAPIdata = await response.Content.ReadAsAsync<ReturnedAPIdata>(); // ReadAsAsync has been deprecated, but not replaced. Handy
string responseBody = await response.Content.ReadAsStringAsync();
// Which one of these fuckers actually works. Use an API, they said. It'll be fun, they said. ARG!
ReturnedAPIdata Arses = System.Text.Json.JsonSerializer.Deserialize<ReturnedAPIdata>(responseBody); // attempt 3
List<ReturnedAPIdata> Cock = JsonConvert.DeserializeObject<List<ReturnedAPIdata>>(responseBody); // attempt 2
ReturnedAPIdata Balls = JsonConvert.DeserializeObject<ReturnedAPIdata>(responseBody); // attempt 1
}
Console.WriteLine("FFFFFFFFFfffff....");
return ThatAPIdata;
}
最后的 Conrole.Writeline 只是一个断点,所以我可以评估哪种反序列化尝试效果最好,我还没有看到有人停下来。