Search code examples
c#asp.net-web-apihttp-posthttpclient

HttpClient PostAsync System.Net.Http.HttpRequestException: An error occurred while sending the request


I am working on a simple console program which consumes a webservice(http). Will post json strings from a txt file.

Tested the snippet below on my own api which was working fine.

Used postman to post a request to the api and did get back a response.

static void Main(string[] args)
{
    //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
    HttpClient client = new HttpClient(); //should be instatiated once per application

    do
    {
        try
        {
            Console.WriteLine("Enter Method:");
            string Method = Console.ReadLine();

            Console.WriteLine("Enter URI:");
            string uri = Console.ReadLine();

            if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
            {
                Console.WriteLine("Enter FilePath:");

                string FilePath = Console.ReadLine();
                iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "File Path : <", FilePath + ">"));

                string str_content = (File.OpenText(@FilePath)).ReadToEnd();
                iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "String data : <", str_content + ">"));

                //StringContent class creates a formatted text appropriate for the http server/client communication
                StringContent httpContent = new StringContent(str_content, System.Text.Encoding.UTF8, "application/json");
                iLog.Log(iLog.EVENT, string.Format("1")); //trace

                try
                {
                    //Some risky client call that will call parallell code / async /TPL or in some way cause an AggregateException 
                    var postTask = client.PostAsync(uri, httpContent);
                    iLog.Log(iLog.EVENT, string.Format("2")); //trace

                    postTask.Wait();
                    iLog.Log(iLog.EVENT, string.Format("3")); //trace

                    //gets the response back from the API service
                    HttpResponseMessage result = postTask.Result;
                    iLog.Log(iLog.EVENT, string.Format("4")); //trace

                    if (result.IsSuccessStatusCode)
                    {
                        iLog.Log(iLog.EVENT, string.Format("5")); //trace

                        //use this if you want a raw json string
                        var readTask = result.Content.ReadAsStringAsync();
                        iLog.Log(iLog.EVENT, string.Format("6")); //trace

                        readTask.Wait();
                        iLog.Log(iLog.EVENT, string.Format("7")); //trace

                        var str_Response = readTask.Result.ToString();
                        iLog.Log(iLog.EVENT, string.Format("8")); //trace
                        
                        Console.WriteLine("WebService Response : \n<" + str_Response + ">");
                        iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "WebService Response : <", str_Response + ">"));
                    }
                    else
                    {
                        Console.WriteLine("Status Code = " + result.StatusCode);
                        iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "StatusCode", result.StatusCode));
                        iLog.Log(iLog.EVENT, string.Format("9")); //trace
                    }

                }
                catch (AggregateException err)
                {
                    foreach (var errInner in err.InnerExceptions)
                    {
                        iLog.Log(iLog.ERROR, string.Format(errInner.ToString())); //trace                                
                    }
                }

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
            iLog.Log(iLog.EVENT, string.Format("{0} | {1}", "Exception", ex.Message.ToString()));
            iLog.Log(iLog.EVENT, string.Format("10")); //trace
        }
        iLog.Log(iLog.EVENT, string.Format("{0} {1}", "END", "----------------------------" + "\n"));
        Console.WriteLine("Do you want to continue?");
    } while (Console.ReadLine().ToUpper() == "Y");

}

Got back Err:

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace ---


Solution

  • Hi was able to get it to work by using Caius Jard suggestion of using the adding restsharp nuget and replacing with the Postman generated code.