在没有身份验证的情况下发出 POST 请求时超时 C#

Timeout while making POST request with no authentication C#

我想向休息服务发出 POST 请求。没有认证,它只有两个定制的header。我的代码如下。我收到错误:

'System.AggregateException' 类型的异常发生在 mscorlib.dll 中,但未在用户代码中处理。

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

你能帮忙吗?代码有什么问题?

 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Accept.Clear();
 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;

您的代码本身看起来没有问题。错误消息表明请求 运行 进入超时,这意味着 HttpClient 等待一段设定的时间,如果服务器没有响应则终止。您是否尝试过对服务器执行 ping 操作以确保它确实已启动并且 运行?

在这种情况下,您可以尝试增加 HttpClient 的超时值(参见此处 https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=netframework-4.8)。

此外,您可以尝试使用其他工具(如 Postman)发送请求,看看问题出在您的代码、您的参数(如超时)还是服务器本身。