0
using System;
using System.Net.Http;

namespace ConsoleAppRest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string url = "http://jsonplaceholder.typicode.com/posts/1/comments";

            GetRequest(url);
        }

        async static void GetRequest(string urlstr)
        {


            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(urlstr))
                {
                   using (HttpContent content = response.Content)
                    {
                        string mycontent = await content.ReadAsStringAsync();
                        Console.WriteLine(mycontent);

                    }

                }
            }

        }

    }
}

I am using above code ,but when i am executing ,i am not getting anything on the console.

To automatically close the console when debugging stops, enable Tools->Options- Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .

I should get the response in json format as below (also same result in browser)

[
 {
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"

  },
  {
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic@sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  },
  {
  ..
  }
]
rick schott
  • 21,012
  • 5
  • 52
  • 81
Penguin Tech
  • 63
  • 1
  • 1
  • 8
  • The obvious answer would be because it's not returning anything. The first step to debugging this would be to observe the network traffic to confirm is anything is actually being returned when your code is run. – Matt Burland Nov 21 '19 at 14:31
  • 1
    also, it's an async method, and you're not awaiting it. so the application ends before the request returns anything. – Glenn van Acker Nov 21 '19 at 14:33
  • GetRequest is async so you need to await GetRequest(url);. This will require that you to make the main method async also. – Cosmin Sontu Nov 21 '19 at 14:34

2 Answers2

1

Your code is async, but you call it from a synchronous method. You need to wait for the result before it is printed, or else your code will just exit.

var task = GetRequest(url);
task.WaitAndUnwrapException();

Read more in this SO post: How to call async

you could also make the main method async, and await your call

await GetRequest(url);
Espen
  • 2,456
  • 1
  • 16
  • 25
-1

Add Console.ReadLine(); after GetRequest(url);

Sandris B
  • 133
  • 6