无法使用 C# 从 API 获得 json 响应

Can't get a json response from an API with C#

我正在学习如何使用 API。我已经能够请求并获得一个安全令牌,并且我能够通过 API 的身份验证以获取对 return 我想要的信息的 GET 请求。我使用下面显示的代码发出我的 GET 请求。

client.BaseAddress = new Uri("https://api.example.com");
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization" ,"Bearer "+ accessToken);
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
HttpResponseMessage response =client.GetAsync"/api/v1/agencies/agencyId/users?email=Test.Test@Test.net").Result;
if (response.IsSuccessStatusCode)
{
    string json = "Need help here";
}

我通过了 API 的身份验证,但就是不知道如何获取 json 数据。我发现了几个使用命令提示符应用程序和本地 API; 的例子。它们似乎都使用 async with wait,但它们似乎在 ASP.Net 网络应用程序中不起作用。

任何人都可以帮助我或展示一个使用网络表单的例子吗?

你可以这样得到 json:

if (response.IsSuccessStatusCode)
{
    string json = response.Content.ReadAsStringAsync().Result;
}

对于异步函数,您可以使用:

if (response.IsSuccessStatusCode)
{
    string json = await response.Content.ReadAsStringAsync();
}