【发布时间】:2020-12-20 13:17:24
【问题描述】:
我正在开发一个使用 webservice(http) 的简单控制台程序。 将从 txt 文件中发布 json 字符串。
在我自己的 api 上测试了下面的 sn-p,效果很好。
使用邮递员向 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& 上下文) 在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- 内部异常堆栈跟踪结束 ---
【问题讨论】:
-
与 Postman 一起使用的是 POST 还是 PUT?
-
正在使用帖子
-
我不知道这个评论是否粗鲁。但是请看一下 c# docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… 的命名约定,这表明你是如何尊重观众的
-
注明会修复,还是很新的。
-
您实际上还可以将 Main 方法的签名更改为
public static async Task Main(string[] args)以便能够利用 async/await 而不是 .Wait/.Result
标签: c# asp.net-web-api http-post httpclient