C
C#2y ago
fooo1

❔ ✅ Why doesn't this basic HttpClient GET request doesn't work as expected?

I do not get anything past making a request. Neither an exception, nor an exception. I'm guessing it's because I'm not properly waiting for async to complete - but in that case what is it lacking? Program.cs
HttpClientLib httpClientLib = new();
httpClientLib.RequestGet();
HttpClientLib httpClientLib = new();
httpClientLib.RequestGet();
HttpClientLib.cs
using System.Net.Http;

public class HttpClientLib
{
public async void RequestGet()
{
try
{
using (var client = new HttpClient()) {
var url = "https://dummy.restapiexample.com/api/v1/employees";
HttpResponseMessage response = await client.GetAsync(url);
Console.WriteLine(response.StatusCode);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Generic exception caught: {ex.Message}");
}
}
}
using System.Net.Http;

public class HttpClientLib
{
public async void RequestGet()
{
try
{
using (var client = new HttpClient()) {
var url = "https://dummy.restapiexample.com/api/v1/employees";
HttpResponseMessage response = await client.GetAsync(url);
Console.WriteLine(response.StatusCode);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Generic exception caught: {ex.Message}");
}
}
}
14 Replies
Pobiega
Pobiega2y ago
async void change that to be async Task and await it at the top level also, don't using var client like that, its bad practice
FusedQyou
FusedQyou2y ago
Why? Does it not log the exception? It should do that
fooo1
fooo1OP2y ago
ahh I see. I wrongly assumed void and Task are both valid types, depending on your needs, but seems async code should always (for beginners atleast) be Task - is that correct? As per your suggestion, changed using to be declerative - using HttpClient client = new();
Pobiega
Pobiega2y ago
no you shouldnt be using a httpclient
FusedQyou
FusedQyou2y ago
It should always return a Task so it can be properly awaited. There are very strict edge cases where you don't need to do that, but you probably won't encounter them. By making it a Task, you can properly await any errors.
Pobiega
Pobiega2y ago
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
using HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);

Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
using HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);

Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
read that top comment you should NOT be creating/disposing HttpClients willy-nilly https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-8.0 yeah, always use Task. async void is for fire and forget event handlers, which this is not. unawaited async operation, so the application probably exits before the http requets is made
FusedQyou
FusedQyou2y ago
Dunno, not enough context
Pobiega
Pobiega2y ago
sure, but thats the most likely answer for it not printing/throwing an exception not to mention that async void swallows all exceptions anyways 😛
fooo1
fooo1OP2y ago
Thank you for the help. Reading through the docs again to understand better
Pobiega
Pobiega2y ago
👍 $close
MODiX
MODiX2y ago
Use the /close command to mark a forum thread as answered
Pobiega
Pobiega2y ago
if thats what you were going for 🙂
fooo1
fooo1OP2y ago
yeapp, will know now
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server