从C#代码发送HTTP请求时挂起
今天,我遇到了一个问题,下面的代码向我的web服务发出了一个简单的POST请求:从C#代码发送HTTP请求时挂起,c#,rest,http,fiddler,C#,Rest,Http,Fiddler,今天,我遇到了一个问题,下面的代码向我的web服务发出了一个简单的POST请求: class Program { static void Main(string[] args) { var response = new HttpClient().PostAsync("http://localhost/myservice", new StringContent("{ \"type\": \"confirmation\" }", Encodin
class Program
{
static void Main(string[] args)
{
var response = new HttpClient().PostAsync("http://localhost/myservice",
new StringContent("{ \"type\": \"confirmation\" }", Encoding.UTF8, "application/json"))
.Result;
Console.WriteLine(response.StatusCode);
}
}
出于某种奇怪的原因,它挂了很长时间。有时它几乎永远挂起,有时它返回0作为状态码。
如果我使用Postman向我的web服务发送相同的请求,我几乎立即得到200 OK
重要提示:
如果Fiddler处于打开状态,它可以正常工作,如果Fiddler未运行,它将停止工作。在HTTP客户端中设置超时,并使用try-catch检查是否有异常,使用Fiddler检查请求和响应。这是调试的最佳方法。如果我设置了超时,当到达timout时,HttpClient抛出
TaskCanceledException
。请设置fiddler并跟踪请求。您可能知道,fiddler不会跟踪从.NET Framework发出的请求到localhost,因此我用我的机器名替换了“localhost”。而且,出于某种奇怪的原因,所有人都开始工作得很好。我仍然觉得奇怪。
var client = new RestClient("http://localhost/myservice");
var request = new RestRequest("api") { Method = Method.POST };
request.AddJsonBody(new { type = "confirmation" });
var response = client.Execute(request);