1

I'm making post request, but my debugger doesn't stop after this line:

var result = await client.PostAsync(_url, data);

My full program

class Program
    {
        static void Main(string[] args)
        {


            var _url = "https://test.test.test:9100/path/path";
            CheckHttpPostAsync(new { id = 123123, username = "testas" });


            async Task CheckHttpPostAsync(object payload)
            {

                    using var client = new HttpClient();
                    var json = JsonConvert.SerializeObject(payload);
                    var data = new StringContent(json, Encoding.UTF8, "application/json");
                    try
                    {
                        var result = await client.PostAsync(_url, data);
                        Console.WriteLine(result);

                    }
                    catch (Exception e)
                    {

                        Console.WriteLine(e);
                    }
            }
        }
    }

and nothing gets written in console, even though im using await

The post request works fine in postman with the same JSON.

edit: added full code

1 Answers1

1

you should await your call to CheckHttpPostAsync and make Main as async Task Main

class Program
{
    static async Task Main(string[] args)
    {
        var _url = "https://test.test.test:9100/path/path";
        await CheckHttpPostAsync(new { id = 123123, username = "testas" });

        async Task CheckHttpPostAsync(object payload)
        {
                using var client = new HttpClient();
                var json = JsonConvert.SerializeObject(payload);
                var data = new StringContent(json, Encoding.UTF8, "application/json");
                try
                {
                    var response = await client.PostAsync(_url, data);
                    string result =  await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);

                }
                catch (Exception e)
                {

                    Console.WriteLine(e);
                }
        }
    }
}
Radik
  • 2,715
  • 1
  • 19
  • 24
  • 1
    In more detail: CheckHttpPostAsync is called but not awaited so - the program ends And once it ends, the async is terminated and - well, why would anything be written as the program has ended ;) So, teh answer is correct - the main method must be async and await. – TomTom May 27 '20 at 17:17
  • 1
    Why do you call Result on ReadAsStringAsync instead of awaiting it? – Francesc Castells May 27 '20 at 17:18
  • 1
    @FrancescCastells yes my bad, updated – Radik May 27 '20 at 18:23