【发布时间】:2019-01-23 11:53:18
【问题描述】:
我正在使用 HttpClient 与具有大量 api 的 web 服务(由我的公司编写)进行交互。 所有的 api 都很好用,除非其中一个(更大和更慢)需要超过 100 秒才能给出答案,过了那个时间我收到以下错误(注意:如果 api 花费少于 100 秒都可以正常工作):
System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: The operation has timed out.
at System.Net.HttpWebRequest+<RunWithTimeoutWorker>d__241`1[T].MoveNext () [0x000c5] in <3e9b3e26c4694baab3f689687ad40612>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00020] in <3e9b3e26c4694baab3f689687ad40612>:0
at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x0041d] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0
--- End of inner exception stack trace ---
at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x00478] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0
所有 IIS 和 web 服务超时都设置为 5 分钟,所以我认为我可以排除这是一个 Web 服务超时问题,并且在应用程序上我将 HttpClient 超时设置为 10 分钟(但即使我设置它也不起作用5 分钟),就像你在下面的代码中看到的那样。我做错了什么?
代码:
var handler = new HttpClientHandler() { CookieContainer = cookie,
MaxRequestContentBufferSize = 256000000,
UseCookies = true,
};
HttpClient newclient = new HttpClient(handler);
newclient.Timeout = new TimeSpan(0, 10, 0); //That DIDN'T WORK :(
// ALL THE CODE I NEED TO BUILD MY JSON INSIDE jSoNToPost
//....
//....
//convert it to JSON acceptible content
HttpContent formContent = new StringContent(jSoNToPost, Encoding.UTF8, "application/json");
var uri = new Uri(Path.Combine(BaseUrl, "BIG_API_NAME"));
var response1 = await newclient.PostAsync(uri, formContent); // <-- THE EXCEPTION IS THROWN HERE!!!!!
if (response1.IsSuccessStatusCode)
{
//Other Stuff
//....
//....
}
else
{
//Other Stuff
//....
//....
}
环境:
Window 10、Visual Studio 2017、Xamarin IOS 和 Android。
编辑 2019-01-23 14:21:
100s的超时时间是HttpClient默认的超时时间,所以
newclient.Timeout = new TimeSpan(0, 10, 0);
不覆盖默认值。
我不明白 InfiniteTimeSpan 是什么,我尝试遵循 that post 中的两个答案。没有成功:( 100s 后仍然显示超时错误。
【问题讨论】:
-
您是否尝试将超时设置为
InfiniteTimeSpan? -
什么是
RunWithTimeoutWorker?是否有可能超时的包装器? -
SushiHangover:droid 和 ios。 @Kay Nelson:我没有实现任何东西,我认为是 HttpClient 内部的东西,InfiniteTimeSpan 在 xamarin 下不存在。
-
@Legion,这个问题将在下个版本的mono中修复,您可以从github.com/mono/mono/issues/12577获取此信息
标签: c# xamarin dotnet-httpclient