Home » c# » rest – Making POST request with no authentication C#

rest – Making POST request with no authentication C#

Posted by: admin February 21, 2020 Leave a comment


I want to make a POST request to a rest service. There is no authentication, it has only two customized header. My code is below. I am getting the error :

An exception of type ‘System.AggregateException’ occurred in mscorlib.dll but was not handled in user code.

“A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond”

May you help ? What is wrong in the code ?

 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 client.DefaultRequestHeaders.Add("id", "8888");
 client.DefaultRequestHeaders.Add("type", "CUSTOMER");
 Uri uri = new Uri(requestUri);
 var ob = new { id= "5", color= "pink" };
 var transferJson = JsonConvert.SerializeObject(ob);
 var content = new StringContent(transferJson, Encoding.UTF8, "application/json");
 HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;
How to&Answers:

Your code itself doesn’t look faulty. The error message suggests that the request ran into a timout, which means that the HttpClient waits for a set period of time and terminates if the server doesn’t respond. Have you tried pinging the server to make sure it’s actually up and running?

It that’s the case you could try to increase the timeout value of your HttpClient (see here https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=netframework-4.8).

Additionally you could try to send the request with another tool like Postman to see whether the issue lies within your code, your parameters (like timeout), or the server itself.