.net RestSharp超时不起作用

fxnxkyjh  于 2022-12-14  发布在  .NET
关注(0)|答案(3)|浏览(565)

我有一个restsharp客户端和请求设置如下:

var request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.Timeout = -1;
request.ReadWriteTimeout = -1;
var url = $"http://{ipAddress}/api/calculate";
var client = new RestClient();
client.BaseUrl = new Uri(url);
client.Timeout = -1;
client.ReadWriteTimeout = -1;
var response = client.Execute(request);

这个请求需要一段时间才能完成,大约30分钟。现在,我知道有更优雅的方法来完成这个请求,但是,对于这个请求,我需要这样做。
此RestSharp客户端和请求在Windows服务内执行。当服务执行请求时,它会引发TimoutException,请求最大超时约为40秒。
由于某种原因,我设置的超时不适用于这种情况。
有人能解决这个问题吗?

aydmsdu9

aydmsdu91#

溶液(版本107+)

var options = new RestClientOptions("baseURL") {
    ThrowOnAnyError = true,
    Timeout = 1000  // 1 second - thanks to @JohnMc
};
var client = new RestClient(options);

旧版本:

将默认超时更改为:5秒-例如-(即5000毫秒):

var client = new RestClient("BaseUrl");
    client.Timeout = 5000; // 5000 milliseconds == 5 seconds
mwg9r5ms

mwg9r5ms2#

设置ReadWriteTimeout的值可能不是你所想的那样。你的值被忽略了,所以你得到了默认值。
根据这个答案,What is default timeout value of RestSharp RestClient? RestSharp在其实现中使用HttpWebRequest
HttpWebRequest的超时属性不能为负HttpWebRequest.Timeout Property
如果您查看RestSharp客户端代码,您会看到以下内容:https://github.com/restsharp/RestSharp/blob/70de357b0b9dfc3926c95d1e69967c7a7cbe874c/RestSharp/RestClient.cs#L452

int readWriteTimeout = request.ReadWriteTimeout > 0
            ? request.ReadWriteTimeout
            : this.ReadWriteTimeout;

        if (readWriteTimeout > 0)
        {
            http.ReadWriteTimeout = readWriteTimeout;
        }

相关问题