3

I am just learning how to work with an API. I have been able to request and get a security token and I am able to get authenticated to the API for a GET request to return the information I want. I use the code shown below to make my GET request.

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";
}

I get authenticated to the API but just can not figure out how to get the json data. I have found several examples that use a command prompt application with a local API; they all seem to use async with wait, but those do not seem to work in an ASP.Net web application.

Can anyone help me out or show an example that is using a web form?

Robert Crovella
  • 143,785
  • 11
  • 213
  • 257
Perry
  • 1,277
  • 2
  • 17
  • 39
  • HttpClient has a [GetStringAsync](https://msdn.microsoft.com/en-us/library/hh551746(v=vs.118).aspx) method. An example of getting the JSON string is shown [in this question](http://stackoverflow.com/questions/34314570/how-to-get-date-and-time-on-asp-net-web-api/34315129#34315129). – mason Dec 16 '15 at 19:55
  • @B.ClayShannon Json.NET won't help you if you don't know how to get the JSON string from the HttpClient in the first place. – mason Dec 16 '15 at 19:55
  • 1
    Maybe we need perry mason to clear this up...oh, wait, you're already here! If Dixon shows up, we can draw the line there. – B. Clay Shannon-B. Crow Raven Dec 16 '15 at 19:56
  • Check this: http://restsharp.org/ – Mate Dec 16 '15 at 19:57
  • 3
    Possible duplicate of [What does HttpResponseMessage return as Json](http://stackoverflow.com/questions/17350074/what-does-httpresponsemessage-return-as-json) – Fraser Crosbie Dec 17 '15 at 03:36

1 Answers1

2

You can get the json like that:

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

for async function, you can use that:

if (response.IsSuccessStatusCode)
{
    string json = await response.Content.ReadAsStringAsync();
}
Thomas
  • 24,234
  • 6
  • 81
  • 125
  • Thank you Thomas your answer was exactly what I needed. I will be on to the next step in this journey which is take that json data and get it into a database. – Perry Dec 17 '15 at 16:20