c# – WebException的根本原因是什么,消息“请求已中止:请求已取消.”

我正在使用HttpClient发出Http请求.我偶尔会看到以下错误:

Exception Type: System.Net.WebException
Error message: The request was aborted: The request was canceled.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
Exception Type: System.Net.Http.HttpRequestException
Error message: An error occurred while sending the request.

我试图了解根本原因是什么.我可以在StackOverflow上找到关于此消息的帖子很多(例如this post),但所有帖子似乎都与查找变通方法有关(通常将KeepAlive设置为false,我不想要),我只是想了解一下错误确实意味着我可以决定是否以及在哪里采取行动.

最佳答案 没有人能说清楚.

启用network client trace可以帮助检测根本原因.

注意:

该文档定义了5个跟踪源,但System.Net的Logging类中有6个:

s_WebTraceSource = new NclTraceSource("System.Net");
s_HttpListenerTraceSource = new NclTraceSource("System.Net.HttpListener"); // not in the documentation
s_SocketsTraceSource = new NclTraceSource("System.Net.Sockets");
s_WebSocketsTraceSource = new NclTraceSource("System.Net.WebSockets");
s_CacheTraceSource = new NclTraceSource("System.Net.Cache");
s_TraceSourceHttpName = new NclTraceSource("System.Net.Http");

全部启用5时的示例日志:

System.Net Verbose: 0 : [9520] WebRequest::Create(http://localhost:9876/)
System.Net Verbose: 0 : [9520] HttpWebRequest#58870012::HttpWebRequest(http://localhost:9876/#363619410)
System.Net Information: 0 : [9520] Current OS installation type is 'Client'.
System.Net Information: 0 : [9520] RAS supported: True
System.Net Verbose: 0 : [9520] Exiting HttpWebRequest#58870012::HttpWebRequest() 
System.Net Verbose: 0 : [9520] Exiting WebRequest::Create()     -> HttpWebRequest#58870012
System.Net Verbose: 0 : [9520] HttpWebRequest#58870012::GetResponse()
System.Net Verbose: 0 : [9520] ServicePoint#33675143::ServicePoint(localhost:9876)
System.Net Information: 0 : [9520] Associating HttpWebRequest#58870012 with ServicePoint#33675143
System.Net Information: 0 : [9520] Associating Connection#34640832 with HttpWebRequest#58870012
System.Net.Sockets Verbose: 0 : [9520] Socket#43332040::Socket(AddressFamily#2)
System.Net.Sockets Verbose: 0 : [9520] Exiting Socket#43332040::Socket() 
System.Net.Sockets Verbose: 0 : [9520] Socket#54444047::Socket(AddressFamily#23)
System.Net.Sockets Verbose: 0 : [9520] Exiting Socket#54444047::Socket() 
System.Net.Sockets Verbose: 0 : [9520] DNS::TryInternalResolve(localhost)
System.Net.Sockets Verbose: 0 : [9520] Socket#43332040::Connect(127.0.0.1:9876#16787179)
System.Net.Sockets Error: 0 : [9520] Socket#43332040::UpdateStatusAfterSocketError() - ConnectionRefused
System.Net.Sockets Error: 0 : [9520] Exception in Socket#43332040::Connect - No connection could be made because the target machine actively refused it 127.0.0.1:9876.
System.Net.Sockets Verbose: 0 : [9520] Socket#43332040::Dispose()
System.Net.Sockets Verbose: 0 : [9520] Socket#54444047::Dispose()
点赞