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

6
  • 1
    How do you call this function CheckHttpPostAsync? Can you show the code? Commented May 27, 2020 at 12:04
  • try var resp = await result.Content.ReadAsStringAsync(); Commented May 27, 2020 at 12:16
  • is your code compilable? using seems syntax error. Commented May 27, 2020 at 12:21
  • Using is fine in latest versions of C# where block is no longer needed. Commented May 27, 2020 at 12:35
  • Is it possible there is an error that is being swallowed on the thread executing the post? I have seen this a few times where an error is happening in the controller processing the post but it never returns Commented May 27, 2020 at 12:37

1 Answer 1

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); } } } } 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Why do you call Result on ReadAsStringAsync instead of awaiting it?
@FrancescCastells yes my bad, updated