HttpClient PostAsync System.Net.Http.HttpRequestException:发送请求时出错

时间:2020-12-20 13:17:24

标签: c# asp.net-web-api http-post httpclient

我正在开发一个使用 webservice(http) 的简单控制台程序。 将从 txt 文件中发布 json 字符串。

在我自己的 api 上测试了下面的代码片段,效果很好。

使用邮递员向 api 发送请求并得到回复。

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");

}

回来了错误:

<块引用>

System.Net.Http.HttpRequestException:发送请求时出错。 ---> System.Net.WebException: 底层连接已关闭:连接意外关闭。 在 System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) 在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- 内部异常堆栈跟踪结束---

1 个答案:

答案 0 :(得分:0)

嗨,通过使用 Caius Jard 的建议,使用添加 restsharp nuget 并替换为 Postman 生成的代码,您可以让它工作。