C# HttpClient.SendAsync throw “An error occurred while sending the request” exception when testing some URLs

If you look at the InnerException you will see that:

“The remote name could not be resolved: ‘www.fc.edu'”

This URL does not work on my browser either.

In order to get an HTTP response you need the client to be able to communicate with the server (even in order to get error 404) and in your case the error occurred at the DNS level.

Some browsers have auto-completion for this kind of cases where if a specific URL is not found, the browser retries with a different suffix/prefix, for example:

try "x"
if didn't work, try "www." + x
if this didn't work try "www." + x + ".com"
if this didn't work try "www." + x + ".net"
if this didn't work try "www." + x + "." + currentRegionSuffix.

But note that you can change your code from:

catch (Exception e)
{

}

To:

catch (HttpRequestException e)
{
    Console.WriteLine(e.InnerException.Message);
}

And you will be able to see what causes your error.

Also, You should never want to catch the generic Exception unless the thrower has thrown the generic Exception, and even than, never catch and do nothing with the exception, at least log it.

Notice than since you wait only for that one task you can use:

urlTester.RunTestAsync().Wait();

Instead of:

Task.WhenAll(urlTester.RunTestAsync());

Task.WhenAll creates a new Task when the given Tasks are completed. in your case you need Task.WaitAll or Task.WhenAll(...).Wait().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)